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;
231 const ALL_DEFAULT_STRING
= '*';
233 /** Fast query, standard limit. */
234 const LIMIT_BIG1
= 500;
235 /** Fast query, apihighlimits limit. */
236 const LIMIT_BIG2
= 5000;
237 /** Slow query, standard limit. */
238 const LIMIT_SML1
= 50;
239 /** Slow query, apihighlimits limit. */
240 const LIMIT_SML2
= 500;
243 * getAllowedParams() flag: When set, the result could take longer to generate,
244 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
247 const GET_VALUES_FOR_HELP
= 1;
249 /** @var array Maps extension paths to info arrays */
250 private static $extensionInfo = null;
253 private $mMainModule;
255 private $mModuleName, $mModulePrefix;
256 private $mSlaveDB = null;
257 private $mParamCache = [];
258 /** @var array|null|bool */
259 private $mModuleSource = false;
262 * @param ApiMain $mainModule
263 * @param string $moduleName Name of this module
264 * @param string $modulePrefix Prefix to use for parameter names
266 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
267 $this->mMainModule
= $mainModule;
268 $this->mModuleName
= $moduleName;
269 $this->mModulePrefix
= $modulePrefix;
271 if ( !$this->isMain() ) {
272 $this->setContext( $mainModule->getContext() );
276 /************************************************************************//**
277 * @name Methods to implement
282 * Evaluates the parameters, performs the requested query, and sets up
283 * the result. Concrete implementations of ApiBase must override this
284 * method to provide whatever functionality their module offers.
285 * Implementations must not produce any output on their own and are not
286 * expected to handle any errors.
288 * The execute() method will be invoked directly by ApiMain immediately
289 * before the result of the module is output. Aside from the
290 * constructor, implementations should assume that no other methods
291 * will be called externally on the module before the result is
294 * The result data should be stored in the ApiResult object available
295 * through getResult().
297 abstract public function execute();
300 * Get the module manager, or null if this module has no sub-modules
302 * @return ApiModuleManager
304 public function getModuleManager() {
309 * If the module may only be used with a certain format module,
310 * it should override this method to return an instance of that formatter.
311 * A value of null means the default format will be used.
312 * @note Do not use this just because you don't want to support non-json
313 * formats. This should be used only when there is a fundamental
314 * requirement for a specific format.
315 * @return mixed Instance of a derived class of ApiFormatBase, or null
317 public function getCustomPrinter() {
322 * Returns usage examples for this module.
324 * Return value has query strings as keys, with values being either strings
325 * (message key), arrays (message key + parameter), or Message objects.
327 * Do not call this base class implementation when overriding this method.
332 protected function getExamplesMessages() {
333 // Fall back to old non-localised method
336 $examples = $this->getExamples();
338 if ( !is_array( $examples ) ) {
339 $examples = [ $examples ];
340 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
341 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
342 !preg_match( '/^\s*api\.php\?/', $examples[0] )
344 // Fix up the ugly "even numbered elements are description, odd
345 // numbered elemts are the link" format (see doc for self::getExamples)
347 $examplesCount = count( $examples );
348 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
349 $tmp[$examples[$i +
1]] = $examples[$i];
354 foreach ( $examples as $k => $v ) {
355 if ( is_numeric( $k ) ) {
360 $msg = self
::escapeWikiText( $v );
361 if ( is_array( $msg ) ) {
362 $msg = implode( ' ', $msg );
366 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
367 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
375 * Return links to more detailed help pages about the module.
376 * @since 1.25, returning boolean false is deprecated
377 * @return string|array
379 public function getHelpUrls() {
384 * Returns an array of allowed parameters (parameter name) => (default
385 * value) or (parameter name) => (array with PARAM_* constants as keys)
386 * Don't call this function directly: use getFinalParams() to allow
387 * hooks to modify parameters as needed.
389 * Some derived classes may choose to handle an integer $flags parameter
390 * in the overriding methods. Callers of this method can pass zero or
391 * more OR-ed flags like GET_VALUES_FOR_HELP.
395 protected function getAllowedParams( /* $flags = 0 */ ) {
396 // int $flags is not declared because it causes "Strict standards"
397 // warning. Most derived classes do not implement it.
402 * Indicates if this module needs maxlag to be checked
405 public function shouldCheckMaxlag() {
410 * Indicates whether this module requires read rights
413 public function isReadMode() {
418 * Indicates whether this module requires write mode
420 * This should return true for modules that may require synchronous database writes.
421 * Modules that do not need such writes should also not rely on master database access,
422 * since only read queries are needed and each master DB is a single point of failure.
423 * Additionally, requests that only need replica DBs can be efficiently routed to any
424 * datacenter via the Promise-Non-Write-API-Action header.
428 public function isWriteMode() {
433 * Indicates whether this module must be called with a POST request
436 public function mustBePosted() {
437 return $this->needsToken() !== false;
441 * Indicates whether this module is deprecated
445 public function isDeprecated() {
450 * Indicates whether this module is "internal"
451 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
455 public function isInternal() {
460 * Returns the token type this module requires in order to execute.
462 * Modules are strongly encouraged to use the core 'csrf' type unless they
463 * have specialized security needs. If the token type is not one of the
464 * core types, you must use the ApiQueryTokensRegisterTypes hook to
467 * Returning a non-falsey value here will force the addition of an
468 * appropriate 'token' parameter in self::getFinalParams(). Also,
469 * self::mustBePosted() must return true when tokens are used.
471 * In previous versions of MediaWiki, true was a valid return value.
472 * Returning true will generate errors indicating that the API module needs
475 * @return string|false
477 public function needsToken() {
482 * Fetch the salt used in the Web UI corresponding to this module.
484 * Only override this if the Web UI uses a token with a non-constant salt.
487 * @param array $params All supplied parameters for the module
488 * @return string|array|null
490 protected function getWebUITokenSalt( array $params ) {
495 * Returns data for HTTP conditional request mechanisms.
498 * @param string $condition Condition being queried:
499 * - last-modified: Return a timestamp representing the maximum of the
500 * last-modified dates for all resources involved in the request. See
501 * RFC 7232 § 2.2 for semantics.
502 * - etag: Return an entity-tag representing the state of all resources involved
503 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
504 * @return string|bool|null As described above, or null if no value is available.
506 public function getConditionalRequestData( $condition ) {
512 /************************************************************************//**
513 * @name Data access methods
518 * Get the name of the module being executed by this instance
521 public function getModuleName() {
522 return $this->mModuleName
;
526 * Get parameter prefix (usually two letters or an empty string).
529 public function getModulePrefix() {
530 return $this->mModulePrefix
;
534 * Get the main module
537 public function getMain() {
538 return $this->mMainModule
;
542 * Returns true if this module is the main module ($this === $this->mMainModule),
546 public function isMain() {
547 return $this === $this->mMainModule
;
551 * Get the parent of this module
553 * @return ApiBase|null
555 public function getParent() {
556 return $this->isMain() ?
null : $this->getMain();
560 * Returns true if the current request breaks the same-origin policy.
562 * For example, json with callbacks.
564 * https://en.wikipedia.org/wiki/Same-origin_policy
569 public function lacksSameOriginSecurity() {
570 // Main module has this method overridden
571 // Safety - avoid infinite loop:
572 if ( $this->isMain() ) {
573 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
576 return $this->getMain()->lacksSameOriginSecurity();
580 * Get the path to this module
585 public function getModulePath() {
586 if ( $this->isMain() ) {
588 } elseif ( $this->getParent()->isMain() ) {
589 return $this->getModuleName();
591 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
596 * Get a module from its module path
599 * @param string $path
600 * @return ApiBase|null
601 * @throws ApiUsageException
603 public function getModuleFromPath( $path ) {
604 $module = $this->getMain();
605 if ( $path === 'main' ) {
609 $parts = explode( '+', $path );
610 if ( count( $parts ) === 1 ) {
611 // In case the '+' was typed into URL, it resolves as a space
612 $parts = explode( ' ', $path );
615 $count = count( $parts );
616 for ( $i = 0; $i < $count; $i++
) {
618 $manager = $parent->getModuleManager();
619 if ( $manager === null ) {
620 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
621 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
623 $module = $manager->getModule( $parts[$i] );
625 if ( $module === null ) {
626 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
628 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
638 * Get the result object
641 public function getResult() {
642 // Main module has getResult() method overridden
643 // Safety - avoid infinite loop:
644 if ( $this->isMain() ) {
645 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
648 return $this->getMain()->getResult();
652 * Get the error formatter
653 * @return ApiErrorFormatter
655 public function getErrorFormatter() {
656 // Main module has getErrorFormatter() method overridden
657 // Safety - avoid infinite loop:
658 if ( $this->isMain() ) {
659 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
662 return $this->getMain()->getErrorFormatter();
666 * Gets a default replica DB connection object
669 protected function getDB() {
670 if ( !isset( $this->mSlaveDB
) ) {
671 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
674 return $this->mSlaveDB
;
678 * Get the continuation manager
679 * @return ApiContinuationManager|null
681 public function getContinuationManager() {
682 // Main module has getContinuationManager() method overridden
683 // Safety - avoid infinite loop:
684 if ( $this->isMain() ) {
685 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
688 return $this->getMain()->getContinuationManager();
692 * Set the continuation manager
693 * @param ApiContinuationManager|null $manager
695 public function setContinuationManager( ApiContinuationManager
$manager = null ) {
696 // Main module has setContinuationManager() method overridden
697 // Safety - avoid infinite loop:
698 if ( $this->isMain() ) {
699 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
702 $this->getMain()->setContinuationManager( $manager );
707 /************************************************************************//**
708 * @name Parameter handling
713 * Indicate if the module supports dynamically-determined parameters that
714 * cannot be included in self::getAllowedParams().
715 * @return string|array|Message|null Return null if the module does not
716 * support additional dynamic parameters, otherwise return a message
719 public function dynamicParameterDocumentation() {
724 * This method mangles parameter name based on the prefix supplied to the constructor.
725 * Override this method to change parameter name during runtime
726 * @param string|string[] $paramName Parameter name
727 * @return string|string[] Prefixed parameter name
728 * @since 1.29 accepts an array of strings
730 public function encodeParamName( $paramName ) {
731 if ( is_array( $paramName ) ) {
732 return array_map( function ( $name ) {
733 return $this->mModulePrefix
. $name;
736 return $this->mModulePrefix
. $paramName;
741 * Using getAllowedParams(), this function makes an array of the values
742 * provided by the user, with key being the name of the variable, and
743 * value - validated value from user or default. limits will not be
744 * parsed if $parseLimit is set to false; use this when the max
745 * limit is not definitive yet, e.g. when getting revisions.
746 * @param bool $parseLimit True by default
749 public function extractRequestParams( $parseLimit = true ) {
750 // Cache parameters, for performance and to avoid T26564.
751 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
752 $params = $this->getFinalParams();
755 if ( $params ) { // getFinalParams() can return false
756 foreach ( $params as $paramName => $paramSettings ) {
757 $results[$paramName] = $this->getParameterFromSettings(
758 $paramName, $paramSettings, $parseLimit );
761 $this->mParamCache
[$parseLimit] = $results;
764 return $this->mParamCache
[$parseLimit];
768 * Get a value for the given parameter
769 * @param string $paramName Parameter name
770 * @param bool $parseLimit See extractRequestParams()
771 * @return mixed Parameter value
773 protected function getParameter( $paramName, $parseLimit = true ) {
774 $paramSettings = $this->getFinalParams()[$paramName];
776 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
780 * Die if none or more than one of a certain set of parameters is set and not false.
782 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
783 * @param string $required,... Names of parameters of which exactly one must be set
785 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
786 $required = func_get_args();
787 array_shift( $required );
789 $intersection = array_intersect( array_keys( array_filter( $params,
790 [ $this, 'parameterNotEmpty' ] ) ), $required );
792 if ( count( $intersection ) > 1 ) {
793 $this->dieWithError( [
794 'apierror-invalidparammix',
795 Message
::listParam( array_map(
797 return '<var>' . $this->encodeParamName( $p ) . '</var>';
799 array_values( $intersection )
801 count( $intersection ),
803 } elseif ( count( $intersection ) == 0 ) {
804 $this->dieWithError( [
805 'apierror-missingparam-one-of',
806 Message
::listParam( array_map(
808 return '<var>' . $this->encodeParamName( $p ) . '</var>';
810 array_values( $required )
818 * Die if more than one of a certain set of parameters is set and not false.
820 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
821 * @param string $required,... Names of parameters of which at most one must be set
823 public function requireMaxOneParameter( $params, $required /*...*/ ) {
824 $required = func_get_args();
825 array_shift( $required );
827 $intersection = array_intersect( array_keys( array_filter( $params,
828 [ $this, 'parameterNotEmpty' ] ) ), $required );
830 if ( count( $intersection ) > 1 ) {
831 $this->dieWithError( [
832 'apierror-invalidparammix',
833 Message
::listParam( array_map(
835 return '<var>' . $this->encodeParamName( $p ) . '</var>';
837 array_values( $intersection )
839 count( $intersection ),
845 * Die if none of a certain set of parameters is set and not false.
848 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
849 * @param string $required,... Names of parameters of which at least one must be set
851 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
852 $required = func_get_args();
853 array_shift( $required );
855 $intersection = array_intersect(
856 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
860 if ( count( $intersection ) == 0 ) {
861 $this->dieWithError( [
862 'apierror-missingparam-at-least-one-of',
863 Message
::listParam( array_map(
865 return '<var>' . $this->encodeParamName( $p ) . '</var>';
867 array_values( $required )
875 * Die if any of the specified parameters were found in the query part of
876 * the URL rather than the post body.
878 * @param string[] $params Parameters to check
879 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
881 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
882 // Skip if $wgDebugAPI is set or we're in internal mode
883 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
887 $queryValues = $this->getRequest()->getQueryValues();
889 foreach ( $params as $param ) {
890 if ( $prefix !== 'noprefix' ) {
891 $param = $this->encodeParamName( $param );
893 if ( array_key_exists( $param, $queryValues ) ) {
894 $badParams[] = $param;
900 [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
906 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
908 * @param object $x Parameter to check is not null/false
911 private function parameterNotEmpty( $x ) {
912 return !is_null( $x ) && $x !== false;
916 * Get a WikiPage object from a title or pageid param, if possible.
917 * Can die, if no param is set or if the title or page id is not valid.
919 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
920 * @param bool|string $load Whether load the object's state from the database:
921 * - false: don't load (if the pageid is given, it will still be loaded)
922 * - 'fromdb': load from a replica DB
923 * - 'fromdbmaster': load from the master database
926 public function getTitleOrPageId( $params, $load = false ) {
927 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
930 if ( isset( $params['title'] ) ) {
931 $titleObj = Title
::newFromText( $params['title'] );
932 if ( !$titleObj ||
$titleObj->isExternal() ) {
933 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
935 if ( !$titleObj->canExist() ) {
936 $this->dieWithError( 'apierror-pagecannotexist' );
938 $pageObj = WikiPage
::factory( $titleObj );
939 if ( $load !== false ) {
940 $pageObj->loadPageData( $load );
942 } elseif ( isset( $params['pageid'] ) ) {
943 if ( $load === false ) {
946 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
948 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
956 * Get a Title object from a title or pageid param, if possible.
957 * Can die, if no param is set or if the title or page id is not valid.
960 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
963 public function getTitleFromTitleOrPageId( $params ) {
964 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
967 if ( isset( $params['title'] ) ) {
968 $titleObj = Title
::newFromText( $params['title'] );
969 if ( !$titleObj ||
$titleObj->isExternal() ) {
970 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
973 } elseif ( isset( $params['pageid'] ) ) {
974 $titleObj = Title
::newFromID( $params['pageid'] );
976 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
984 * Return true if we're to watch the page, false if not, null if no change.
985 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
986 * @param Title $titleObj The page under consideration
987 * @param string $userOption The user option to consider when $watchlist=preferences.
988 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
991 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
992 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
994 switch ( $watchlist ) {
1002 # If the user is already watching, don't bother checking
1003 if ( $userWatching ) {
1006 # If no user option was passed, use watchdefault and watchcreations
1007 if ( is_null( $userOption ) ) {
1008 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1009 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1012 # Watch the article based on the user preference
1013 return $this->getUser()->getBoolOption( $userOption );
1016 return $userWatching;
1019 return $userWatching;
1024 * Using the settings determine the value for the given parameter
1026 * @param string $paramName Parameter name
1027 * @param array|mixed $paramSettings Default value or an array of settings
1028 * using PARAM_* constants.
1029 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1030 * @return mixed Parameter value
1032 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1033 // Some classes may decide to change parameter names
1034 $encParamName = $this->encodeParamName( $paramName );
1037 if ( !is_array( $paramSettings ) ) {
1039 self
::PARAM_DFLT
=> $paramSettings,
1043 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1044 ?
$paramSettings[self
::PARAM_DFLT
]
1046 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1047 ?
$paramSettings[self
::PARAM_ISMULTI
]
1049 $multiLimit1 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] )
1050 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT1
]
1052 $multiLimit2 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] )
1053 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT2
]
1055 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1056 ?
$paramSettings[self
::PARAM_TYPE
]
1058 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1059 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1061 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1062 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1064 $deprecatedValues = isset( $paramSettings[self
::PARAM_DEPRECATED_VALUES
] )
1065 ?
$paramSettings[self
::PARAM_DEPRECATED_VALUES
]
1067 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1068 ?
$paramSettings[self
::PARAM_REQUIRED
]
1070 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1071 ?
$paramSettings[self
::PARAM_ALL
]
1074 // When type is not given, and no choices, the type is the same as $default
1075 if ( !isset( $type ) ) {
1076 if ( isset( $default ) ) {
1077 $type = gettype( $default );
1079 $type = 'NULL'; // allow everything
1083 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1084 $this->getMain()->markParamsSensitive( $encParamName );
1087 if ( $type == 'boolean' ) {
1088 if ( isset( $default ) && $default !== false ) {
1089 // Having a default value of anything other than 'false' is not allowed
1092 "Boolean param $encParamName's default is set to '$default'. " .
1093 'Boolean parameters must default to false.'
1097 $value = $this->getMain()->getCheck( $encParamName );
1098 } elseif ( $type == 'upload' ) {
1099 if ( isset( $default ) ) {
1100 // Having a default value is not allowed
1103 "File upload param $encParamName's default is set to " .
1104 "'$default'. File upload parameters may not have a default." );
1107 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1109 $value = $this->getMain()->getUpload( $encParamName );
1110 if ( !$value->exists() ) {
1111 // This will get the value without trying to normalize it
1112 // (because trying to normalize a large binary file
1113 // accidentally uploaded as a field fails spectacularly)
1114 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1115 if ( $value !== null ) {
1116 $this->dieWithError(
1117 [ 'apierror-badupload', $encParamName ],
1118 "badupload_{$encParamName}"
1123 $value = $this->getMain()->getVal( $encParamName, $default );
1125 if ( isset( $value ) && $type == 'namespace' ) {
1126 $type = MWNamespace
::getValidNamespaces();
1127 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1128 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1130 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1132 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1133 // specify all namespaces irrespective of PARAM_ALL.
1136 if ( isset( $value ) && $type == 'submodule' ) {
1137 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1138 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1140 $type = $this->getModuleManager()->getNames( $paramName );
1144 $request = $this->getMain()->getRequest();
1145 $rawValue = $request->getRawVal( $encParamName );
1146 if ( $rawValue === null ) {
1147 $rawValue = $default;
1150 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1151 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1153 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1154 // done by WebRequest for $_GET. Let's call that a feature.
1155 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1157 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1161 // Check for NFC normalization, and warn
1162 if ( $rawValue !== $value ) {
1163 $this->handleParamNormalization( $paramName, $value, $rawValue );
1167 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1168 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1171 "For param $encParamName, PARAM_ALL collides with a possible value" );
1173 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1174 $value = $this->parseMultiValue(
1178 is_array( $type ) ?
$type : null,
1179 $allowAll ?
$allSpecifier : null,
1185 if ( isset( $value ) ) {
1186 // More validation only when choices were not given
1187 // choices were validated in parseMultiValue()
1188 if ( !is_array( $type ) ) {
1190 case 'NULL': // nothing to do
1195 if ( $required && $value === '' ) {
1196 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1199 case 'integer': // Force everything using intval() and optionally validate limits
1200 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1201 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1202 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1203 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1205 if ( is_array( $value ) ) {
1206 $value = array_map( 'intval', $value );
1207 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1208 foreach ( $value as &$v ) {
1209 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1213 $value = intval( $value );
1214 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1215 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1220 if ( !$parseLimit ) {
1221 // Don't do any validation whatsoever
1224 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1225 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1229 "MAX1 or MAX2 are not defined for the limit $encParamName"
1233 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1235 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1236 if ( $value == 'max' ) {
1237 $value = $this->getMain()->canApiHighLimits()
1238 ?
$paramSettings[self
::PARAM_MAX2
]
1239 : $paramSettings[self
::PARAM_MAX
];
1240 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1242 $value = intval( $value );
1243 $this->validateLimit(
1247 $paramSettings[self
::PARAM_MAX
],
1248 $paramSettings[self
::PARAM_MAX2
]
1254 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1258 if ( is_array( $value ) ) {
1259 foreach ( $value as $key => $val ) {
1260 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1263 $value = $this->validateTimestamp( $value, $encParamName );
1267 if ( is_array( $value ) ) {
1268 foreach ( $value as $key => $val ) {
1269 $value[$key] = $this->validateUser( $val, $encParamName );
1272 $value = $this->validateUser( $value, $encParamName );
1275 case 'upload': // nothing to do
1278 // If change tagging was requested, check that the tags are valid.
1279 if ( !is_array( $value ) && !$multi ) {
1280 $value = [ $value ];
1282 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1283 if ( !$tagsStatus->isGood() ) {
1284 $this->dieStatus( $tagsStatus );
1288 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1292 // Throw out duplicates if requested
1293 if ( !$dupes && is_array( $value ) ) {
1294 $value = array_unique( $value );
1297 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1298 foreach ( (array)$value as $val ) {
1299 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1300 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1302 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1303 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1305 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1306 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1308 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1309 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1314 // Set a warning if a deprecated parameter has been passed
1315 if ( $deprecated && $value !== false ) {
1316 $feature = $encParamName;
1318 while ( !$m->isMain() ) {
1319 $p = $m->getParent();
1320 $name = $m->getModuleName();
1321 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1322 $feature = "{$param}={$name}&{$feature}";
1325 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1328 // Set a warning if a deprecated parameter value has been passed
1329 $usedDeprecatedValues = $deprecatedValues && $value !== false
1330 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1332 if ( $usedDeprecatedValues ) {
1333 $feature = "$encParamName=";
1335 while ( !$m->isMain() ) {
1336 $p = $m->getParent();
1337 $name = $m->getModuleName();
1338 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1339 $feature = "{$param}={$name}&{$feature}";
1342 foreach ( $usedDeprecatedValues as $v ) {
1343 $msg = $deprecatedValues[$v];
1344 if ( $msg === true ) {
1345 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1347 $this->addDeprecation( $msg, "$feature$v" );
1350 } elseif ( $required ) {
1351 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1358 * Handle when a parameter was Unicode-normalized
1360 * @param string $paramName Unprefixed parameter name
1361 * @param string $value Input that will be used.
1362 * @param string $rawValue Input before normalization.
1364 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1365 $encParamName = $this->encodeParamName( $paramName );
1366 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1370 * Split a multi-valued parameter string, like explode()
1372 * @param string $value
1376 protected function explodeMultiValue( $value, $limit ) {
1377 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1379 $value = substr( $value, 1 );
1384 return explode( $sep, $value, $limit );
1388 * Return an array of values that were given in a 'a|b|c' notation,
1389 * after it optionally validates them against the list allowed values.
1391 * @param string $valueName The name of the parameter (for error
1393 * @param mixed $value The value being parsed
1394 * @param bool $allowMultiple Can $value contain more than one value
1396 * @param string[]|null $allowedValues An array of values to check against. If
1397 * null, all values are accepted.
1398 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1399 * if this behavior should not be allowed
1400 * @param int|null $limit1 Maximum number of values, for normal users.
1401 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1402 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1404 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1405 $allSpecifier = null, $limit1 = null, $limit2 = null
1407 if ( ( $value === '' ||
$value === "\x1f" ) && $allowMultiple ) {
1410 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1411 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1413 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1414 // because it unstubs $wgUser
1415 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1416 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1420 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1421 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1423 return $allowedValues;
1426 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1427 $this->addDeprecation(
1428 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1429 "too-many-$valueName-for-{$this->getModulePath()}"
1433 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1434 // T35482 - Allow entries with | in them for non-multiple values
1435 if ( in_array( $value, $allowedValues, true ) ) {
1439 $values = array_map( function ( $v ) {
1440 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1441 }, $allowedValues );
1442 $this->dieWithError( [
1443 'apierror-multival-only-one-of',
1445 Message
::listParam( $values ),
1447 ], "multival_$valueName" );
1450 if ( is_array( $allowedValues ) ) {
1451 // Check for unknown values
1452 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1453 if ( count( $unknown ) ) {
1454 if ( $allowMultiple ) {
1455 $this->addWarning( [
1456 'apiwarn-unrecognizedvalues',
1458 Message
::listParam( $unknown, 'comma' ),
1462 $this->dieWithError(
1463 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1464 "unknown_$valueName"
1468 // Now throw them out
1469 $valuesList = array_intersect( $valuesList, $allowedValues );
1472 return $allowMultiple ?
$valuesList : $valuesList[0];
1476 * Validate the value against the minimum and user/bot maximum limits.
1477 * Prints usage info on failure.
1478 * @param string $paramName Parameter name
1479 * @param int &$value Parameter value
1480 * @param int|null $min Minimum value
1481 * @param int|null $max Maximum value for users
1482 * @param int $botMax Maximum value for sysops/bots
1483 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1485 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1486 $enforceLimits = false
1488 if ( !is_null( $min ) && $value < $min ) {
1489 $msg = ApiMessage
::create(
1490 [ 'apierror-integeroutofrange-belowminimum',
1491 $this->encodeParamName( $paramName ), $min, $value ],
1492 'integeroutofrange',
1493 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1495 $this->warnOrDie( $msg, $enforceLimits );
1499 // Minimum is always validated, whereas maximum is checked only if not
1500 // running in internal call mode
1501 if ( $this->getMain()->isInternalMode() ) {
1505 // Optimization: do not check user's bot status unless really needed -- skips db query
1506 // assumes $botMax >= $max
1507 if ( !is_null( $max ) && $value > $max ) {
1508 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1509 if ( $value > $botMax ) {
1510 $msg = ApiMessage
::create(
1511 [ 'apierror-integeroutofrange-abovebotmax',
1512 $this->encodeParamName( $paramName ), $botMax, $value ],
1513 'integeroutofrange',
1514 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1516 $this->warnOrDie( $msg, $enforceLimits );
1520 $msg = ApiMessage
::create(
1521 [ 'apierror-integeroutofrange-abovemax',
1522 $this->encodeParamName( $paramName ), $max, $value ],
1523 'integeroutofrange',
1524 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1526 $this->warnOrDie( $msg, $enforceLimits );
1533 * Validate and normalize parameters of type 'timestamp'
1534 * @param string $value Parameter value
1535 * @param string $encParamName Parameter name
1536 * @return string Validated and normalized parameter
1538 protected function validateTimestamp( $value, $encParamName ) {
1539 // Confusing synonyms for the current time accepted by wfTimestamp()
1540 // (wfTimestamp() also accepts various non-strings and the string of 14
1541 // ASCII NUL bytes, but those can't get here)
1543 $this->addDeprecation(
1544 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1545 'unclear-"now"-timestamp'
1547 return wfTimestamp( TS_MW
);
1550 // Explicit synonym for the current time
1551 if ( $value === 'now' ) {
1552 return wfTimestamp( TS_MW
);
1555 $timestamp = wfTimestamp( TS_MW
, $value );
1556 if ( $timestamp === false ) {
1557 $this->dieWithError(
1558 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1559 "badtimestamp_{$encParamName}"
1567 * Validate the supplied token.
1570 * @param string $token Supplied token
1571 * @param array $params All supplied parameters for the module
1573 * @throws MWException
1575 final public function validateToken( $token, array $params ) {
1576 $tokenType = $this->needsToken();
1577 $salts = ApiQueryTokens
::getTokenTypeSalts();
1578 if ( !isset( $salts[$tokenType] ) ) {
1579 throw new MWException(
1580 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1581 'without registering it'
1585 $tokenObj = ApiQueryTokens
::getToken(
1586 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1588 if ( $tokenObj->match( $token ) ) {
1592 $webUiSalt = $this->getWebUITokenSalt( $params );
1593 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1605 * Validate and normalize parameters of type 'user'
1606 * @param string $value Parameter value
1607 * @param string $encParamName Parameter name
1608 * @return string Validated and normalized parameter
1610 private function validateUser( $value, $encParamName ) {
1611 if ( ExternalUserNames
::isExternal( $value ) && User
::newFromName( $value, false ) ) {
1615 $titleObj = Title
::makeTitleSafe( NS_USER
, $value );
1618 $value = $titleObj->getText();
1622 !User
::isValidUserName( $value ) &&
1623 // We allow ranges as well, for blocks.
1624 !IP
::isIPAddress( $value ) &&
1625 // See comment for User::isIP. We don't just call that function
1626 // here because it also returns true for things like
1627 // 300.300.300.300 that are neither valid usernames nor valid IP
1630 '/^' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.xxx$/',
1634 $this->dieWithError(
1635 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1636 "baduser_{$encParamName}"
1645 /************************************************************************//**
1646 * @name Utility methods
1651 * Set a watch (or unwatch) based the based on a watchlist parameter.
1652 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1653 * @param Title $titleObj The article's title to change
1654 * @param string $userOption The user option to consider when $watch=preferences
1656 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1657 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1658 if ( $value === null ) {
1662 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1666 * Truncate an array to a certain length.
1667 * @param array &$arr Array to truncate
1668 * @param int $limit Maximum length
1669 * @return bool True if the array was truncated, false otherwise
1671 public static function truncateArray( &$arr, $limit ) {
1673 while ( count( $arr ) > $limit ) {
1682 * Gets the user for whom to get the watchlist
1684 * @param array $params
1687 public function getWatchlistUser( $params ) {
1688 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1689 $user = User
::newFromName( $params['owner'], false );
1690 if ( !( $user && $user->getId() ) ) {
1691 $this->dieWithError(
1692 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1695 $token = $user->getOption( 'watchlisttoken' );
1696 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1697 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1700 if ( !$this->getUser()->isLoggedIn() ) {
1701 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1703 $this->checkUserRightsAny( 'viewmywatchlist' );
1704 $user = $this->getUser();
1711 * A subset of wfEscapeWikiText for BC texts
1714 * @param string|array $v
1715 * @return string|array
1717 private static function escapeWikiText( $v ) {
1718 if ( is_array( $v ) ) {
1719 return array_map( 'self::escapeWikiText', $v );
1722 '__' => '__', '{' => '{', '}' => '}',
1723 '[[Category:' => '[[:Category:',
1724 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1730 * Create a Message from a string or array
1732 * A string is used as a message key. An array has the message key as the
1733 * first value and message parameters as subsequent values.
1736 * @param string|array|Message $msg
1737 * @param IContextSource $context
1738 * @param array $params
1739 * @return Message|null
1741 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1742 if ( is_string( $msg ) ) {
1743 $msg = wfMessage( $msg );
1744 } elseif ( is_array( $msg ) ) {
1745 $msg = call_user_func_array( 'wfMessage', $msg );
1747 if ( !$msg instanceof Message
) {
1751 $msg->setContext( $context );
1753 $msg->params( $params );
1760 * Turn an array of message keys or key+param arrays into a Status
1762 * @param array $errors
1763 * @param User|null $user
1766 public function errorArrayToStatus( array $errors, User
$user = null ) {
1767 if ( $user === null ) {
1768 $user = $this->getUser();
1771 $status = Status
::newGood();
1772 foreach ( $errors as $error ) {
1773 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1774 $status->fatal( ApiMessage
::create(
1777 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1779 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1780 $status->fatal( ApiMessage
::create(
1781 'apierror-autoblocked',
1783 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1785 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1786 $status->fatal( ApiMessage
::create(
1787 'apierror-systemblocked',
1789 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1792 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1800 /************************************************************************//**
1801 * @name Warning and error reporting
1806 * Add a warning for this module.
1808 * Users should monitor this section to notice any changes in API. Multiple
1809 * calls to this function will result in multiple warning messages.
1811 * If $msg is not an ApiMessage, the message code will be derived from the
1812 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1815 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1816 * @param string|null $code See ApiErrorFormatter::addWarning()
1817 * @param array|null $data See ApiErrorFormatter::addWarning()
1819 public function addWarning( $msg, $code = null, $data = null ) {
1820 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1824 * Add a deprecation warning for this module.
1826 * A combination of $this->addWarning() and $this->logFeatureUsage()
1829 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1830 * @param string|null $feature See ApiBase::logFeatureUsage()
1831 * @param array|null $data See ApiErrorFormatter::addWarning()
1833 public function addDeprecation( $msg, $feature, $data = [] ) {
1834 $data = (array)$data;
1835 if ( $feature !== null ) {
1836 $data['feature'] = $feature;
1837 $this->logFeatureUsage( $feature );
1839 $this->addWarning( $msg, 'deprecation', $data );
1841 // No real need to deduplicate here, ApiErrorFormatter does that for
1842 // us (assuming the hook is deterministic).
1843 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1844 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1845 if ( count( $msgs ) > 1 ) {
1846 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1847 $msg = ( new RawMessage( $key ) )->params( $msgs );
1849 $msg = reset( $msgs );
1851 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1855 * Add an error for this module without aborting
1857 * If $msg is not an ApiMessage, the message code will be derived from the
1858 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1860 * @note If you want to abort processing, use self::dieWithError() instead.
1862 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1863 * @param string|null $code See ApiErrorFormatter::addError()
1864 * @param array|null $data See ApiErrorFormatter::addError()
1866 public function addError( $msg, $code = null, $data = null ) {
1867 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1871 * Add warnings and/or errors from a Status
1873 * @note If you want to abort processing, use self::dieStatus() instead.
1875 * @param StatusValue $status
1876 * @param string[] $types 'warning' and/or 'error'
1878 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1879 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1883 * Abort execution with an error
1885 * If $msg is not an ApiMessage, the message code will be derived from the
1886 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1889 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1890 * @param string|null $code See ApiErrorFormatter::addError()
1891 * @param array|null $data See ApiErrorFormatter::addError()
1892 * @param int|null $httpCode HTTP error code to use
1893 * @throws ApiUsageException always
1895 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1896 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1900 * Abort execution with an error derived from an exception
1903 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1904 * @param array $options See ApiErrorFormatter::getMessageFromException()
1905 * @throws ApiUsageException always
1907 public function dieWithException( $exception, array $options = [] ) {
1908 $this->dieWithError(
1909 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1914 * Adds a warning to the output, else dies
1916 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1917 * @param bool $enforceLimits Whether this is an enforce (die)
1919 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1920 if ( $enforceLimits ) {
1921 $this->dieWithError( $msg );
1923 $this->addWarning( $msg );
1928 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1929 * error handler and die with an error message including block info.
1932 * @param Block $block The block used to generate the ApiUsageException
1933 * @throws ApiUsageException always
1935 public function dieBlocked( Block
$block ) {
1936 // Die using the appropriate message depending on block type
1937 if ( $block->getType() == Block
::TYPE_AUTO
) {
1938 $this->dieWithError(
1939 'apierror-autoblocked',
1941 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1944 $this->dieWithError(
1947 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1953 * Throw an ApiUsageException based on the Status object.
1956 * @since 1.29 Accepts a StatusValue
1957 * @param StatusValue $status
1958 * @throws ApiUsageException always
1960 public function dieStatus( StatusValue
$status ) {
1961 if ( $status->isGood() ) {
1962 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1965 // ApiUsageException needs a fatal status, but this method has
1966 // historically accepted any non-good status. Convert it if necessary.
1967 $status->setOK( false );
1968 if ( !$status->getErrorsByType( 'error' ) ) {
1969 $newStatus = Status
::newGood();
1970 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1971 call_user_func_array(
1972 [ $newStatus, 'fatal' ],
1973 array_merge( [ $err['message'] ], $err['params'] )
1976 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1977 $newStatus->fatal( 'unknownerror-nocode' );
1979 $status = $newStatus;
1982 throw new ApiUsageException( $this, $status );
1986 * Helper function for readonly errors
1988 * @throws ApiUsageException always
1990 public function dieReadOnly() {
1991 $this->dieWithError(
1992 'apierror-readonly',
1994 [ 'readonlyreason' => wfReadOnlyReason() ]
1999 * Helper function for permission-denied errors
2001 * @param string|string[] $rights
2002 * @param User|null $user
2003 * @throws ApiUsageException if the user doesn't have any of the rights.
2004 * The error message is based on $rights[0].
2006 public function checkUserRightsAny( $rights, $user = null ) {
2008 $user = $this->getUser();
2010 $rights = (array)$rights;
2011 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
2012 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2017 * Helper function for permission-denied errors
2019 * @param Title $title
2020 * @param string|string[] $actions
2021 * @param User|null $user
2022 * @throws ApiUsageException if the user doesn't have all of the rights.
2024 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2026 $user = $this->getUser();
2030 foreach ( (array)$actions as $action ) {
2031 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2034 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2039 * Will only set a warning instead of failing if the global $wgDebugAPI
2040 * is set to true. Otherwise behaves exactly as self::dieWithError().
2043 * @param string|array|Message $msg
2044 * @param string|null $code
2045 * @param array|null $data
2046 * @param int|null $httpCode
2047 * @throws ApiUsageException
2049 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2050 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2051 $this->dieWithError( $msg, $code, $data, $httpCode );
2053 $this->addWarning( $msg, $code, $data );
2058 * Die with the 'badcontinue' error.
2060 * This call is common enough to make it into the base method.
2062 * @param bool $condition Will only die if this value is true
2063 * @throws ApiUsageException
2066 protected function dieContinueUsageIf( $condition ) {
2068 $this->dieWithError( 'apierror-badcontinue' );
2073 * Internal code errors should be reported with this method
2074 * @param string $method Method or function name
2075 * @param string $message Error message
2076 * @throws MWException always
2078 protected static function dieDebug( $method, $message ) {
2079 throw new MWException( "Internal error in $method: $message" );
2083 * Write logging information for API features to a debug log, for usage
2085 * @note Consider using $this->addDeprecation() instead to both warn and log.
2086 * @param string $feature Feature being used.
2088 public function logFeatureUsage( $feature ) {
2089 $request = $this->getRequest();
2090 $s = '"' . addslashes( $feature ) . '"' .
2091 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2092 ' "' . $request->getIP() . '"' .
2093 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2094 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2095 wfDebugLog( 'api-feature-usage', $s, 'private' );
2100 /************************************************************************//**
2101 * @name Help message generation
2106 * Return the summary message.
2108 * This is a one-line description of the module, suitable for display in a
2112 * @return string|array|Message
2114 protected function getSummaryMessage() {
2115 return "apihelp-{$this->getModulePath()}-summary";
2119 * Return the extended help text message.
2121 * This is additional text to display at the top of the help section, below
2125 * @return string|array|Message
2127 protected function getExtendedDescription() {
2129 "apihelp-{$this->getModulePath()}-extended-description",
2130 'api-help-no-extended-description',
2135 * Get final module summary
2137 * Ideally this will just be the getSummaryMessage(). However, for
2138 * backwards compatibility, if that message does not exist then the first
2139 * line of wikitext from the description message will be used instead.
2144 public function getFinalSummary() {
2145 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2146 $this->getModulePrefix(),
2147 $this->getModuleName(),
2148 $this->getModulePath(),
2150 if ( !$msg->exists() ) {
2151 wfDeprecated( 'API help "description" messages', '1.30' );
2152 $msg = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2153 $this->getModulePrefix(),
2154 $this->getModuleName(),
2155 $this->getModulePath(),
2157 $msg = self
::makeMessage( 'rawmessage', $this->getContext(), [
2158 preg_replace( '/\n.*/s', '', $msg->text() )
2165 * Get final module description, after hooks have had a chance to tweak it as
2168 * @since 1.25, returns Message[] rather than string[]
2171 public function getFinalDescription() {
2172 $desc = $this->getDescription();
2174 // Avoid PHP 7.1 warning of passing $this by reference
2176 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2177 $desc = self
::escapeWikiText( $desc );
2178 if ( is_array( $desc ) ) {
2179 $desc = implode( "\n", $desc );
2181 $desc = (string)$desc;
2184 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2185 $this->getModulePrefix(),
2186 $this->getModuleName(),
2187 $this->getModulePath(),
2189 $extendedDescription = self
::makeMessage(
2190 $this->getExtendedDescription(), $this->getContext(), [
2191 $this->getModulePrefix(),
2192 $this->getModuleName(),
2193 $this->getModulePath(),
2197 if ( $summary->exists() ) {
2198 $msgs = [ $summary, $extendedDescription ];
2200 wfDeprecated( 'API help "description" messages', '1.30' );
2201 $description = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2202 $this->getModulePrefix(),
2203 $this->getModuleName(),
2204 $this->getModulePath(),
2206 if ( !$description->exists() ) {
2207 $description = $this->msg( 'api-help-fallback-description', $desc );
2209 $msgs = [ $description ];
2212 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2218 * Get final list of parameters, after hooks have had a chance to
2219 * tweak it as needed.
2221 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2222 * @return array|bool False on no parameters
2223 * @since 1.21 $flags param added
2225 public function getFinalParams( $flags = 0 ) {
2226 $params = $this->getAllowedParams( $flags );
2231 if ( $this->needsToken() ) {
2232 $params['token'] = [
2233 self
::PARAM_TYPE
=> 'string',
2234 self
::PARAM_REQUIRED
=> true,
2235 self
::PARAM_SENSITIVE
=> true,
2236 self
::PARAM_HELP_MSG
=> [
2237 'api-help-param-token',
2238 $this->needsToken(),
2240 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2243 // Avoid PHP 7.1 warning of passing $this by reference
2245 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2251 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2254 * @since 1.25, returns array of Message[] rather than array of string[]
2255 * @return array Keys are parameter names, values are arrays of Message objects
2257 public function getFinalParamDescription() {
2258 $prefix = $this->getModulePrefix();
2259 $name = $this->getModuleName();
2260 $path = $this->getModulePath();
2262 $desc = $this->getParamDescription();
2264 // Avoid PHP 7.1 warning of passing $this by reference
2266 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2271 $desc = self
::escapeWikiText( $desc );
2273 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2275 foreach ( $params as $param => $settings ) {
2276 if ( !is_array( $settings ) ) {
2280 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2281 if ( is_array( $d ) ) {
2282 // Special handling for prop parameters
2283 $d = array_map( function ( $line ) {
2284 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2285 $line = "\n;{$m[1]}:{$m[2]}";
2289 $d = implode( ' ', $d );
2292 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2293 $msg = $settings[self
::PARAM_HELP_MSG
];
2295 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2296 if ( !$msg->exists() ) {
2297 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2300 $msg = self
::makeMessage( $msg, $this->getContext(),
2301 [ $prefix, $param, $name, $path ] );
2303 self
::dieDebug( __METHOD__
,
2304 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2306 $msgs[$param] = [ $msg ];
2308 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2309 $settings[self
::PARAM_TYPE
] === 'submodule'
2311 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2312 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2314 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2316 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2317 $map[$submoduleName] = $prefix . $submoduleName;
2322 $deprecatedSubmodules = [];
2323 foreach ( $map as $v => $m ) {
2324 $arr = &$submodules;
2325 $isDeprecated = false;
2328 $submod = $this->getModuleFromPath( $m );
2330 $summary = $submod->getFinalSummary();
2331 $isDeprecated = $submod->isDeprecated();
2332 if ( $isDeprecated ) {
2333 $arr = &$deprecatedSubmodules;
2336 } catch ( ApiUsageException
$ex ) {
2340 $key = $summary->getKey();
2341 $params = $summary->getParams();
2343 $key = 'api-help-undocumented-module';
2346 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2347 $arr[] = $m->setContext( $this->getContext() );
2349 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2350 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2351 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2352 self
::dieDebug( __METHOD__
,
2353 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2355 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2356 self
::dieDebug( __METHOD__
,
2357 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2358 'ApiBase::PARAM_TYPE is an array' );
2361 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2362 $deprecatedValues = isset( $settings[self
::PARAM_DEPRECATED_VALUES
] )
2363 ?
$settings[self
::PARAM_DEPRECATED_VALUES
]
2366 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2367 if ( isset( $valueMsgs[$value] ) ) {
2368 $msg = $valueMsgs[$value];
2370 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2372 $m = self
::makeMessage( $msg, $this->getContext(),
2373 [ $prefix, $param, $name, $path, $value ] );
2375 $m = new ApiHelpParamValueMessage(
2377 [ $m->getKey(), 'api-help-param-no-description' ],
2379 isset( $deprecatedValues[$value] )
2381 $msgs[$param][] = $m->setContext( $this->getContext() );
2383 self
::dieDebug( __METHOD__
,
2384 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2389 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2390 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2391 self
::dieDebug( __METHOD__
,
2392 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2394 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2395 $m = self
::makeMessage( $m, $this->getContext(),
2396 [ $prefix, $param, $name, $path ] );
2398 $msgs[$param][] = $m;
2400 self
::dieDebug( __METHOD__
,
2401 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2407 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2413 * Generates the list of flags for the help screen and for action=paraminfo
2415 * Corresponding messages: api-help-flag-deprecated,
2416 * api-help-flag-internal, api-help-flag-readrights,
2417 * api-help-flag-writerights, api-help-flag-mustbeposted
2421 protected function getHelpFlags() {
2424 if ( $this->isDeprecated() ) {
2425 $flags[] = 'deprecated';
2427 if ( $this->isInternal() ) {
2428 $flags[] = 'internal';
2430 if ( $this->isReadMode() ) {
2431 $flags[] = 'readrights';
2433 if ( $this->isWriteMode() ) {
2434 $flags[] = 'writerights';
2436 if ( $this->mustBePosted() ) {
2437 $flags[] = 'mustbeposted';
2444 * Returns information about the source of this module, if known
2446 * Returned array is an array with the following keys:
2447 * - path: Install path
2448 * - name: Extension name, or "MediaWiki" for core
2449 * - namemsg: (optional) i18n message key for a display name
2450 * - license-name: (optional) Name of license
2452 * @return array|null
2454 protected function getModuleSourceInfo() {
2457 if ( $this->mModuleSource
!== false ) {
2458 return $this->mModuleSource
;
2461 // First, try to find where the module comes from...
2462 $rClass = new ReflectionClass( $this );
2463 $path = $rClass->getFileName();
2466 $this->mModuleSource
= null;
2469 $path = realpath( $path ) ?
: $path;
2471 // Build map of extension directories to extension info
2472 if ( self
::$extensionInfo === null ) {
2473 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2474 self
::$extensionInfo = [
2475 realpath( __DIR__
) ?
: __DIR__
=> [
2477 'name' => 'MediaWiki',
2478 'license-name' => 'GPL-2.0-or-later',
2480 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2481 realpath( $extDir ) ?
: $extDir => null,
2487 'license-name' => null,
2489 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2490 foreach ( $group as $ext ) {
2491 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2492 // This shouldn't happen, but does anyway.
2496 $extpath = $ext['path'];
2497 if ( !is_dir( $extpath ) ) {
2498 $extpath = dirname( $extpath );
2500 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2501 array_intersect_key( $ext, $keep );
2504 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2505 $extpath = $ext['path'];
2506 if ( !is_dir( $extpath ) ) {
2507 $extpath = dirname( $extpath );
2509 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2510 array_intersect_key( $ext, $keep );
2514 // Now traverse parent directories until we find a match or run out of
2517 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2519 $this->mModuleSource
= self
::$extensionInfo[$path];
2520 return $this->mModuleSource
;
2524 $path = dirname( $path );
2525 } while ( $path !== $oldpath );
2527 // No idea what extension this might be.
2528 $this->mModuleSource
= null;
2533 * Called from ApiHelp before the pieces are joined together and returned.
2535 * This exists mainly for ApiMain to add the Permissions and Credits
2536 * sections. Other modules probably don't need it.
2538 * @param string[] &$help Array of help data
2539 * @param array $options Options passed to ApiHelp::getHelp
2540 * @param array &$tocData If a TOC is being generated, this array has keys
2541 * as anchors in the page and values as for Linker::generateTOC().
2543 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2548 /************************************************************************//**
2554 * Returns the description string for this module
2556 * Ignored if an i18n message exists for
2557 * "apihelp-{$this->getModulePath()}-description".
2559 * @deprecated since 1.25
2560 * @return Message|string|array|false
2562 protected function getDescription() {
2567 * Returns an array of parameter descriptions.
2569 * For each parameter, ignored if an i18n message exists for the parameter.
2570 * By default that message is
2571 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2572 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2573 * self::getFinalParams().
2575 * @deprecated since 1.25
2576 * @return array|bool False on no parameter descriptions
2578 protected function getParamDescription() {
2583 * Returns usage examples for this module.
2585 * Return value as an array is either:
2586 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2588 * - sequential numeric keys with even-numbered keys being display-text
2589 * and odd-numbered keys being partial urls
2590 * - partial URLs as keys with display-text (string or array-to-be-joined)
2592 * Return value as a string is the same as an array with a numeric key and
2593 * that value, and boolean false means "no examples".
2595 * @deprecated since 1.25, use getExamplesMessages() instead
2596 * @return bool|string|array
2598 protected function getExamples() {
2603 * @deprecated since 1.25
2605 public function profileIn() {
2606 // No wfDeprecated() yet because extensions call this and might need to
2607 // keep doing so for BC.
2611 * @deprecated since 1.25
2613 public function profileOut() {
2614 // No wfDeprecated() yet because extensions call this and might need to
2615 // keep doing so for BC.
2619 * @deprecated since 1.25
2621 public function safeProfileOut() {
2622 wfDeprecated( __METHOD__
, '1.25' );
2626 * @deprecated since 1.25
2628 public function profileDBIn() {
2629 wfDeprecated( __METHOD__
, '1.25' );
2633 * @deprecated since 1.25
2635 public function profileDBOut() {
2636 wfDeprecated( __METHOD__
, '1.25' );
2640 * Call wfTransactionalTimeLimit() if this request was POSTed
2643 protected function useTransactionalTimeLimit() {
2644 if ( $this->getRequest()->wasPosted() ) {
2645 wfTransactionalTimeLimit();
2650 * @deprecated since 1.29, use ApiBase::addWarning() instead
2651 * @param string $warning Warning message
2653 public function setWarning( $warning ) {
2654 wfDeprecated( __METHOD__
, '1.29' );
2655 $msg = new ApiRawMessage( $warning, 'warning' );
2656 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2660 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2661 * error handler and die with an error message.
2663 * @deprecated since 1.29, use self::dieWithError() instead
2664 * @param string $description One-line human-readable description of the
2665 * error condition, e.g., "The API requires a valid action parameter"
2666 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2667 * automated identification of the error, e.g., 'unknown_action'
2668 * @param int $httpRespCode HTTP response code
2669 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2670 * @throws ApiUsageException always
2672 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2673 wfDeprecated( __METHOD__
, '1.29' );
2674 $this->dieWithError(
2675 new RawMessage( '$1', [ $description ] ),
2683 * Get error (as code, string) from a Status object.
2686 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2687 * @param Status $status
2688 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2689 * @return array Array of code and error string
2690 * @throws MWException
2692 public function getErrorFromStatus( $status, &$extraData = null ) {
2693 wfDeprecated( __METHOD__
, '1.29' );
2694 if ( $status->isGood() ) {
2695 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2698 $errors = $status->getErrorsByType( 'error' );
2700 // No errors? Assume the warnings should be treated as errors
2701 $errors = $status->getErrorsByType( 'warning' );
2704 // Still no errors? Punt
2705 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2708 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2709 $msg = $errors[0]['message'];
2711 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2713 if ( !$msg instanceof IApiMessage
) {
2714 $key = $msg->getKey();
2715 $params = $msg->getParams();
2716 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2717 $msg = ApiMessage
::create( $params );
2722 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2727 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2728 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2729 * API codes and message texts, and a few interfaces required poking
2730 * something in here. Now we're repurposing it to map those same strings
2731 * to i18n messages, and declaring that any interface that requires poking
2732 * at this is broken and needs replacing ASAP.
2734 private static $messageMap = [
2735 'unknownerror' => 'apierror-unknownerror',
2736 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2737 'ns-specialprotected' => 'ns-specialprotected',
2738 'protectedinterface' => 'protectedinterface',
2739 'namespaceprotected' => 'namespaceprotected',
2740 'customcssprotected' => 'customcssprotected',
2741 'customjsprotected' => 'customjsprotected',
2742 'cascadeprotected' => 'cascadeprotected',
2743 'protectedpagetext' => 'protectedpagetext',
2744 'protect-cantedit' => 'protect-cantedit',
2745 'deleteprotected' => 'deleteprotected',
2746 'badaccess-group0' => 'badaccess-group0',
2747 'badaccess-groups' => 'badaccess-groups',
2748 'titleprotected' => 'titleprotected',
2749 'nocreate-loggedin' => 'nocreate-loggedin',
2750 'nocreatetext' => 'nocreatetext',
2751 'movenologintext' => 'movenologintext',
2752 'movenotallowed' => 'movenotallowed',
2753 'confirmedittext' => 'confirmedittext',
2754 'blockedtext' => 'apierror-blocked',
2755 'autoblockedtext' => 'apierror-autoblocked',
2756 'systemblockedtext' => 'apierror-systemblocked',
2757 'actionthrottledtext' => 'apierror-ratelimited',
2758 'alreadyrolled' => 'alreadyrolled',
2759 'cantrollback' => 'cantrollback',
2760 'readonlytext' => 'readonlytext',
2761 'sessionfailure' => 'sessionfailure',
2762 'cannotdelete' => 'cannotdelete',
2763 'notanarticle' => 'apierror-missingtitle',
2764 'selfmove' => 'selfmove',
2765 'immobile_namespace' => 'apierror-immobilenamespace',
2766 'articleexists' => 'articleexists',
2767 'hookaborted' => 'hookaborted',
2768 'cantmove-titleprotected' => 'cantmove-titleprotected',
2769 'imagenocrossnamespace' => 'imagenocrossnamespace',
2770 'imagetypemismatch' => 'imagetypemismatch',
2771 'ip_range_invalid' => 'ip_range_invalid',
2772 'range_block_disabled' => 'range_block_disabled',
2773 'nosuchusershort' => 'nosuchusershort',
2774 'badipaddress' => 'badipaddress',
2775 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2776 'ipb_already_blocked' => 'ipb_already_blocked',
2777 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2778 'ipb_cant_unblock' => 'ipb_cant_unblock',
2779 'mailnologin' => 'apierror-cantsend',
2780 'ipbblocked' => 'ipbblocked',
2781 'ipbnounblockself' => 'ipbnounblockself',
2782 'usermaildisabled' => 'usermaildisabled',
2783 'blockedemailuser' => 'apierror-blockedfrommail',
2784 'notarget' => 'apierror-notarget',
2785 'noemail' => 'noemail',
2786 'rcpatroldisabled' => 'rcpatroldisabled',
2787 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2788 'delete-toobig' => 'delete-toobig',
2789 'movenotallowedfile' => 'movenotallowedfile',
2790 'userrights-no-interwiki' => 'userrights-no-interwiki',
2791 'userrights-nodatabase' => 'userrights-nodatabase',
2792 'nouserspecified' => 'nouserspecified',
2793 'noname' => 'noname',
2794 'summaryrequired' => 'apierror-summaryrequired',
2795 'import-rootpage-invalid' => 'import-rootpage-invalid',
2796 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2797 'readrequired' => 'apierror-readapidenied',
2798 'writedisabled' => 'apierror-noapiwrite',
2799 'writerequired' => 'apierror-writeapidenied',
2800 'missingparam' => 'apierror-missingparam',
2801 'invalidtitle' => 'apierror-invalidtitle',
2802 'nosuchpageid' => 'apierror-nosuchpageid',
2803 'nosuchrevid' => 'apierror-nosuchrevid',
2804 'nosuchuser' => 'nosuchusershort',
2805 'invaliduser' => 'apierror-invaliduser',
2806 'invalidexpiry' => 'apierror-invalidexpiry',
2807 'pastexpiry' => 'apierror-pastexpiry',
2808 'create-titleexists' => 'apierror-create-titleexists',
2809 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2810 'cantblock' => 'apierror-cantblock',
2811 'canthide' => 'apierror-canthide',
2812 'cantblock-email' => 'apierror-cantblock-email',
2813 'cantunblock' => 'apierror-permissiondenied-generic',
2814 'cannotundelete' => 'cannotundelete',
2815 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2816 'createonly-exists' => 'apierror-articleexists',
2817 'nocreate-missing' => 'apierror-missingtitle',
2818 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2819 'nosuchrcid' => 'apierror-nosuchrcid',
2820 'nosuchlogid' => 'apierror-nosuchlogid',
2821 'protect-invalidaction' => 'apierror-protect-invalidaction',
2822 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2823 'toofewexpiries' => 'apierror-toofewexpiries',
2824 'cantimport' => 'apierror-cantimport',
2825 'cantimport-upload' => 'apierror-cantimport-upload',
2826 'importnofile' => 'importnofile',
2827 'importuploaderrorsize' => 'importuploaderrorsize',
2828 'importuploaderrorpartial' => 'importuploaderrorpartial',
2829 'importuploaderrortemp' => 'importuploaderrortemp',
2830 'importcantopen' => 'importcantopen',
2831 'import-noarticle' => 'import-noarticle',
2832 'importbadinterwiki' => 'importbadinterwiki',
2833 'import-unknownerror' => 'apierror-import-unknownerror',
2834 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2835 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2836 'mustbeposted' => 'apierror-mustbeposted',
2837 'show' => 'apierror-show',
2838 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2839 'invalidoldimage' => 'apierror-invalidoldimage',
2840 'nodeleteablefile' => 'apierror-nodeleteablefile',
2841 'fileexists-forbidden' => 'fileexists-forbidden',
2842 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2843 'filerevert-badversion' => 'filerevert-badversion',
2844 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2845 'noimageredirect-logged' => 'apierror-noimageredirect',
2846 'spamdetected' => 'apierror-spamdetected',
2847 'contenttoobig' => 'apierror-contenttoobig',
2848 'noedit-anon' => 'apierror-noedit-anon',
2849 'noedit' => 'apierror-noedit',
2850 'wasdeleted' => 'apierror-pagedeleted',
2851 'blankpage' => 'apierror-emptypage',
2852 'editconflict' => 'editconflict',
2853 'hashcheckfailed' => 'apierror-badmd5',
2854 'missingtext' => 'apierror-notext',
2855 'emptynewsection' => 'apierror-emptynewsection',
2856 'revwrongpage' => 'apierror-revwrongpage',
2857 'undo-failure' => 'undo-failure',
2858 'content-not-allowed-here' => 'content-not-allowed-here',
2859 'edit-hook-aborted' => 'edit-hook-aborted',
2860 'edit-gone-missing' => 'edit-gone-missing',
2861 'edit-conflict' => 'edit-conflict',
2862 'edit-already-exists' => 'edit-already-exists',
2863 'invalid-file-key' => 'apierror-invalid-file-key',
2864 'nouploadmodule' => 'apierror-nouploadmodule',
2865 'uploaddisabled' => 'uploaddisabled',
2866 'copyuploaddisabled' => 'copyuploaddisabled',
2867 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2868 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2869 'filename-tooshort' => 'filename-tooshort',
2870 'filename-toolong' => 'filename-toolong',
2871 'illegal-filename' => 'illegal-filename',
2872 'filetype-missing' => 'filetype-missing',
2873 'mustbeloggedin' => 'apierror-mustbeloggedin',
2877 * @deprecated do not use
2878 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2879 * @return ApiMessage
2881 private function parseMsgInternal( $error ) {
2882 $msg = Message
::newFromSpecifier( $error );
2883 if ( !$msg instanceof IApiMessage
) {
2884 $key = $msg->getKey();
2885 if ( isset( self
::$messageMap[$key] ) ) {
2886 $params = $msg->getParams();
2887 array_unshift( $params, self
::$messageMap[$key] );
2889 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2891 $msg = ApiMessage
::create( $params );
2897 * Return the error message related to a certain array
2898 * @deprecated since 1.29
2899 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2900 * @return array [ 'code' => code, 'info' => info ]
2902 public function parseMsg( $error ) {
2903 wfDeprecated( __METHOD__
, '1.29' );
2904 // Check whether someone passed the whole array, instead of one element as
2905 // documented. This breaks if it's actually an array of fallback keys, but
2906 // that's long-standing misbehavior introduced in r87627 to incorrectly
2908 if ( is_array( $error ) ) {
2909 $first = reset( $error );
2910 if ( is_array( $first ) ) {
2911 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2916 $msg = $this->parseMsgInternal( $error );
2918 'code' => $msg->getApiCode(),
2919 'info' => ApiErrorFormatter
::stripMarkup(
2920 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2922 'data' => $msg->getApiData()
2927 * Output the error message related to a certain array
2928 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2929 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2930 * @throws ApiUsageException always
2932 public function dieUsageMsg( $error ) {
2933 wfDeprecated( __METHOD__
, '1.29' );
2934 $this->dieWithError( $this->parseMsgInternal( $error ) );
2938 * Will only set a warning instead of failing if the global $wgDebugAPI
2939 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2940 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2941 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2942 * @throws ApiUsageException
2945 public function dieUsageMsgOrDebug( $error ) {
2946 wfDeprecated( __METHOD__
, '1.29' );
2947 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2951 * Return the description message.
2953 * This is additional text to display on the help page after the summary.
2955 * @deprecated since 1.30
2956 * @return string|array|Message
2958 protected function getDescriptionMessage() {
2960 "apihelp-{$this->getModulePath()}-description",
2961 "apihelp-{$this->getModulePath()}-summary",
2969 * For really cool vim folding this needs to be at the end:
2970 * vim: foldmarker=@{,@} foldmethod=marker