5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 use Wikimedia\Rdbms\IDatabase
;
30 * This abstract class implements many basic API functions, and is the base of
32 * The class functions are divided into several areas of functionality:
34 * Module parameters: Derived classes can define getAllowedParams() to specify
35 * which parameters to expect, how to parse and validate them.
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase
extends ContextSource
{
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
192 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
193 * always sensitive regardless of the value of this field.
196 const PARAM_SENSITIVE
= 19;
199 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
200 * Keys are the deprecated parameter values, values define the warning
201 * message to emit: either boolean true (to use a default message) or a
202 * $msg for ApiBase::makeMessage().
205 const PARAM_DEPRECATED_VALUES
= 20;
208 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
211 const PARAM_ISMULTI_LIMIT1
= 21;
214 * (integer) Maximum number of values, for users with the apihighimits right.
215 * Must be used with PARAM_ISMULTI.
218 const PARAM_ISMULTI_LIMIT2
= 22;
221 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
224 const PARAM_MAX_BYTES
= 23;
227 * (integer) Maximum length of a string in characters (unicode codepoints).
230 const PARAM_MAX_CHARS
= 24;
234 const ALL_DEFAULT_STRING
= '*';
236 /** Fast query, standard limit. */
237 const LIMIT_BIG1
= 500;
238 /** Fast query, apihighlimits limit. */
239 const LIMIT_BIG2
= 5000;
240 /** Slow query, standard limit. */
241 const LIMIT_SML1
= 50;
242 /** Slow query, apihighlimits limit. */
243 const LIMIT_SML2
= 500;
246 * getAllowedParams() flag: When set, the result could take longer to generate,
247 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
250 const GET_VALUES_FOR_HELP
= 1;
252 /** @var array Maps extension paths to info arrays */
253 private static $extensionInfo = null;
256 private $mMainModule;
258 private $mModuleName, $mModulePrefix;
259 private $mSlaveDB = null;
260 private $mParamCache = [];
261 /** @var array|null|bool */
262 private $mModuleSource = false;
265 * @param ApiMain $mainModule
266 * @param string $moduleName Name of this module
267 * @param string $modulePrefix Prefix to use for parameter names
269 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
270 $this->mMainModule
= $mainModule;
271 $this->mModuleName
= $moduleName;
272 $this->mModulePrefix
= $modulePrefix;
274 if ( !$this->isMain() ) {
275 $this->setContext( $mainModule->getContext() );
279 /************************************************************************//**
280 * @name Methods to implement
285 * Evaluates the parameters, performs the requested query, and sets up
286 * the result. Concrete implementations of ApiBase must override this
287 * method to provide whatever functionality their module offers.
288 * Implementations must not produce any output on their own and are not
289 * expected to handle any errors.
291 * The execute() method will be invoked directly by ApiMain immediately
292 * before the result of the module is output. Aside from the
293 * constructor, implementations should assume that no other methods
294 * will be called externally on the module before the result is
297 * The result data should be stored in the ApiResult object available
298 * through getResult().
300 abstract public function execute();
303 * Get the module manager, or null if this module has no sub-modules
305 * @return ApiModuleManager
307 public function getModuleManager() {
312 * If the module may only be used with a certain format module,
313 * it should override this method to return an instance of that formatter.
314 * A value of null means the default format will be used.
315 * @note Do not use this just because you don't want to support non-json
316 * formats. This should be used only when there is a fundamental
317 * requirement for a specific format.
318 * @return mixed Instance of a derived class of ApiFormatBase, or null
320 public function getCustomPrinter() {
325 * Returns usage examples for this module.
327 * Return value has query strings as keys, with values being either strings
328 * (message key), arrays (message key + parameter), or Message objects.
330 * Do not call this base class implementation when overriding this method.
335 protected function getExamplesMessages() {
336 // Fall back to old non-localised method
339 $examples = $this->getExamples();
341 if ( !is_array( $examples ) ) {
342 $examples = [ $examples ];
343 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
344 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
345 !preg_match( '/^\s*api\.php\?/', $examples[0] )
347 // Fix up the ugly "even numbered elements are description, odd
348 // numbered elemts are the link" format (see doc for self::getExamples)
350 $examplesCount = count( $examples );
351 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
352 $tmp[$examples[$i +
1]] = $examples[$i];
357 foreach ( $examples as $k => $v ) {
358 if ( is_numeric( $k ) ) {
363 $msg = self
::escapeWikiText( $v );
364 if ( is_array( $msg ) ) {
365 $msg = implode( ' ', $msg );
369 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
370 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
378 * Return links to more detailed help pages about the module.
379 * @since 1.25, returning boolean false is deprecated
380 * @return string|array
382 public function getHelpUrls() {
387 * Returns an array of allowed parameters (parameter name) => (default
388 * value) or (parameter name) => (array with PARAM_* constants as keys)
389 * Don't call this function directly: use getFinalParams() to allow
390 * hooks to modify parameters as needed.
392 * Some derived classes may choose to handle an integer $flags parameter
393 * in the overriding methods. Callers of this method can pass zero or
394 * more OR-ed flags like GET_VALUES_FOR_HELP.
398 protected function getAllowedParams( /* $flags = 0 */ ) {
399 // int $flags is not declared because it causes "Strict standards"
400 // warning. Most derived classes do not implement it.
405 * Indicates if this module needs maxlag to be checked
408 public function shouldCheckMaxlag() {
413 * Indicates whether this module requires read rights
416 public function isReadMode() {
421 * Indicates whether this module requires write mode
423 * This should return true for modules that may require synchronous database writes.
424 * Modules that do not need such writes should also not rely on master database access,
425 * since only read queries are needed and each master DB is a single point of failure.
426 * Additionally, requests that only need replica DBs can be efficiently routed to any
427 * datacenter via the Promise-Non-Write-API-Action header.
431 public function isWriteMode() {
436 * Indicates whether this module must be called with a POST request
439 public function mustBePosted() {
440 return $this->needsToken() !== false;
444 * Indicates whether this module is deprecated
448 public function isDeprecated() {
453 * Indicates whether this module is "internal"
454 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
458 public function isInternal() {
463 * Returns the token type this module requires in order to execute.
465 * Modules are strongly encouraged to use the core 'csrf' type unless they
466 * have specialized security needs. If the token type is not one of the
467 * core types, you must use the ApiQueryTokensRegisterTypes hook to
470 * Returning a non-falsey value here will force the addition of an
471 * appropriate 'token' parameter in self::getFinalParams(). Also,
472 * self::mustBePosted() must return true when tokens are used.
474 * In previous versions of MediaWiki, true was a valid return value.
475 * Returning true will generate errors indicating that the API module needs
478 * @return string|false
480 public function needsToken() {
485 * Fetch the salt used in the Web UI corresponding to this module.
487 * Only override this if the Web UI uses a token with a non-constant salt.
490 * @param array $params All supplied parameters for the module
491 * @return string|array|null
493 protected function getWebUITokenSalt( array $params ) {
498 * Returns data for HTTP conditional request mechanisms.
501 * @param string $condition Condition being queried:
502 * - last-modified: Return a timestamp representing the maximum of the
503 * last-modified dates for all resources involved in the request. See
504 * RFC 7232 § 2.2 for semantics.
505 * - etag: Return an entity-tag representing the state of all resources involved
506 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
507 * @return string|bool|null As described above, or null if no value is available.
509 public function getConditionalRequestData( $condition ) {
515 /************************************************************************//**
516 * @name Data access methods
521 * Get the name of the module being executed by this instance
524 public function getModuleName() {
525 return $this->mModuleName
;
529 * Get parameter prefix (usually two letters or an empty string).
532 public function getModulePrefix() {
533 return $this->mModulePrefix
;
537 * Get the main module
540 public function getMain() {
541 return $this->mMainModule
;
545 * Returns true if this module is the main module ($this === $this->mMainModule),
549 public function isMain() {
550 return $this === $this->mMainModule
;
554 * Get the parent of this module
556 * @return ApiBase|null
558 public function getParent() {
559 return $this->isMain() ?
null : $this->getMain();
563 * Returns true if the current request breaks the same-origin policy.
565 * For example, json with callbacks.
567 * https://en.wikipedia.org/wiki/Same-origin_policy
572 public function lacksSameOriginSecurity() {
573 // Main module has this method overridden
574 // Safety - avoid infinite loop:
575 if ( $this->isMain() ) {
576 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
579 return $this->getMain()->lacksSameOriginSecurity();
583 * Get the path to this module
588 public function getModulePath() {
589 if ( $this->isMain() ) {
591 } elseif ( $this->getParent()->isMain() ) {
592 return $this->getModuleName();
594 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
599 * Get a module from its module path
602 * @param string $path
603 * @return ApiBase|null
604 * @throws ApiUsageException
606 public function getModuleFromPath( $path ) {
607 $module = $this->getMain();
608 if ( $path === 'main' ) {
612 $parts = explode( '+', $path );
613 if ( count( $parts ) === 1 ) {
614 // In case the '+' was typed into URL, it resolves as a space
615 $parts = explode( ' ', $path );
618 $count = count( $parts );
619 for ( $i = 0; $i < $count; $i++
) {
621 $manager = $parent->getModuleManager();
622 if ( $manager === null ) {
623 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
624 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
626 $module = $manager->getModule( $parts[$i] );
628 if ( $module === null ) {
629 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
631 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
641 * Get the result object
644 public function getResult() {
645 // Main module has getResult() method overridden
646 // Safety - avoid infinite loop:
647 if ( $this->isMain() ) {
648 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
651 return $this->getMain()->getResult();
655 * Get the error formatter
656 * @return ApiErrorFormatter
658 public function getErrorFormatter() {
659 // Main module has getErrorFormatter() method overridden
660 // Safety - avoid infinite loop:
661 if ( $this->isMain() ) {
662 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
665 return $this->getMain()->getErrorFormatter();
669 * Gets a default replica DB connection object
672 protected function getDB() {
673 if ( !isset( $this->mSlaveDB
) ) {
674 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
677 return $this->mSlaveDB
;
681 * Get the continuation manager
682 * @return ApiContinuationManager|null
684 public function getContinuationManager() {
685 // Main module has getContinuationManager() method overridden
686 // Safety - avoid infinite loop:
687 if ( $this->isMain() ) {
688 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
691 return $this->getMain()->getContinuationManager();
695 * Set the continuation manager
696 * @param ApiContinuationManager|null $manager
698 public function setContinuationManager( $manager ) {
699 // Main module has setContinuationManager() method overridden
700 // Safety - avoid infinite loop:
701 if ( $this->isMain() ) {
702 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
705 $this->getMain()->setContinuationManager( $manager );
710 /************************************************************************//**
711 * @name Parameter handling
716 * Indicate if the module supports dynamically-determined parameters that
717 * cannot be included in self::getAllowedParams().
718 * @return string|array|Message|null Return null if the module does not
719 * support additional dynamic parameters, otherwise return a message
722 public function dynamicParameterDocumentation() {
727 * This method mangles parameter name based on the prefix supplied to the constructor.
728 * Override this method to change parameter name during runtime
729 * @param string|string[] $paramName Parameter name
730 * @return string|string[] Prefixed parameter name
731 * @since 1.29 accepts an array of strings
733 public function encodeParamName( $paramName ) {
734 if ( is_array( $paramName ) ) {
735 return array_map( function ( $name ) {
736 return $this->mModulePrefix
. $name;
739 return $this->mModulePrefix
. $paramName;
744 * Using getAllowedParams(), this function makes an array of the values
745 * provided by the user, with key being the name of the variable, and
746 * value - validated value from user or default. limits will not be
747 * parsed if $parseLimit is set to false; use this when the max
748 * limit is not definitive yet, e.g. when getting revisions.
749 * @param bool $parseLimit True by default
752 public function extractRequestParams( $parseLimit = true ) {
753 // Cache parameters, for performance and to avoid T26564.
754 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
755 $params = $this->getFinalParams();
758 if ( $params ) { // getFinalParams() can return false
759 foreach ( $params as $paramName => $paramSettings ) {
760 $results[$paramName] = $this->getParameterFromSettings(
761 $paramName, $paramSettings, $parseLimit );
764 $this->mParamCache
[$parseLimit] = $results;
767 return $this->mParamCache
[$parseLimit];
771 * Get a value for the given parameter
772 * @param string $paramName Parameter name
773 * @param bool $parseLimit See extractRequestParams()
774 * @return mixed Parameter value
776 protected function getParameter( $paramName, $parseLimit = true ) {
777 $paramSettings = $this->getFinalParams()[$paramName];
779 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
783 * Die if none or more than one of a certain set of parameters is set and not false.
785 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
786 * @param string $required,... Names of parameters of which exactly one must be set
788 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
789 $required = func_get_args();
790 array_shift( $required );
792 $intersection = array_intersect( array_keys( array_filter( $params,
793 [ $this, 'parameterNotEmpty' ] ) ), $required );
795 if ( count( $intersection ) > 1 ) {
796 $this->dieWithError( [
797 'apierror-invalidparammix',
798 Message
::listParam( array_map(
800 return '<var>' . $this->encodeParamName( $p ) . '</var>';
802 array_values( $intersection )
804 count( $intersection ),
806 } elseif ( count( $intersection ) == 0 ) {
807 $this->dieWithError( [
808 'apierror-missingparam-one-of',
809 Message
::listParam( array_map(
811 return '<var>' . $this->encodeParamName( $p ) . '</var>';
813 array_values( $required )
821 * Die if more than one of a certain set of parameters is set and not false.
823 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
824 * @param string $required,... Names of parameters of which at most one must be set
826 public function requireMaxOneParameter( $params, $required /*...*/ ) {
827 $required = func_get_args();
828 array_shift( $required );
830 $intersection = array_intersect( array_keys( array_filter( $params,
831 [ $this, 'parameterNotEmpty' ] ) ), $required );
833 if ( count( $intersection ) > 1 ) {
834 $this->dieWithError( [
835 'apierror-invalidparammix',
836 Message
::listParam( array_map(
838 return '<var>' . $this->encodeParamName( $p ) . '</var>';
840 array_values( $intersection )
842 count( $intersection ),
848 * Die if none of a certain set of parameters is set and not false.
851 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
852 * @param string $required,... Names of parameters of which at least one must be set
854 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
855 $required = func_get_args();
856 array_shift( $required );
858 $intersection = array_intersect(
859 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
863 if ( count( $intersection ) == 0 ) {
864 $this->dieWithError( [
865 'apierror-missingparam-at-least-one-of',
866 Message
::listParam( array_map(
868 return '<var>' . $this->encodeParamName( $p ) . '</var>';
870 array_values( $required )
878 * Die if any of the specified parameters were found in the query part of
879 * the URL rather than the post body.
881 * @param string[] $params Parameters to check
882 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
884 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
885 // Skip if $wgDebugAPI is set or we're in internal mode
886 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
890 $queryValues = $this->getRequest()->getQueryValues();
892 foreach ( $params as $param ) {
893 if ( $prefix !== 'noprefix' ) {
894 $param = $this->encodeParamName( $param );
896 if ( array_key_exists( $param, $queryValues ) ) {
897 $badParams[] = $param;
903 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
909 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
911 * @param object $x Parameter to check is not null/false
914 private function parameterNotEmpty( $x ) {
915 return !is_null( $x ) && $x !== false;
919 * Get a WikiPage object from a title or pageid param, if possible.
920 * Can die, if no param is set or if the title or page id is not valid.
922 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
923 * @param bool|string $load Whether load the object's state from the database:
924 * - false: don't load (if the pageid is given, it will still be loaded)
925 * - 'fromdb': load from a replica DB
926 * - 'fromdbmaster': load from the master database
929 public function getTitleOrPageId( $params, $load = false ) {
930 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
933 if ( isset( $params['title'] ) ) {
934 $titleObj = Title
::newFromText( $params['title'] );
935 if ( !$titleObj ||
$titleObj->isExternal() ) {
936 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
938 if ( !$titleObj->canExist() ) {
939 $this->dieWithError( 'apierror-pagecannotexist' );
941 $pageObj = WikiPage
::factory( $titleObj );
942 if ( $load !== false ) {
943 $pageObj->loadPageData( $load );
945 } elseif ( isset( $params['pageid'] ) ) {
946 if ( $load === false ) {
949 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
951 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
959 * Get a Title object from a title or pageid param, if possible.
960 * Can die, if no param is set or if the title or page id is not valid.
963 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
966 public function getTitleFromTitleOrPageId( $params ) {
967 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
970 if ( isset( $params['title'] ) ) {
971 $titleObj = Title
::newFromText( $params['title'] );
972 if ( !$titleObj ||
$titleObj->isExternal() ) {
973 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
976 } elseif ( isset( $params['pageid'] ) ) {
977 $titleObj = Title
::newFromID( $params['pageid'] );
979 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
987 * Return true if we're to watch the page, false if not, null if no change.
988 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
989 * @param Title $titleObj The page under consideration
990 * @param string $userOption The user option to consider when $watchlist=preferences.
991 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
994 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
995 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
997 switch ( $watchlist ) {
1005 # If the user is already watching, don't bother checking
1006 if ( $userWatching ) {
1009 # If no user option was passed, use watchdefault and watchcreations
1010 if ( is_null( $userOption ) ) {
1011 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1012 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1015 # Watch the article based on the user preference
1016 return $this->getUser()->getBoolOption( $userOption );
1019 return $userWatching;
1022 return $userWatching;
1027 * Using the settings determine the value for the given parameter
1029 * @param string $paramName Parameter name
1030 * @param array|mixed $paramSettings Default value or an array of settings
1031 * using PARAM_* constants.
1032 * @param bool $parseLimit Parse limit?
1033 * @return mixed Parameter value
1035 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1036 // Some classes may decide to change parameter names
1037 $encParamName = $this->encodeParamName( $paramName );
1040 if ( !is_array( $paramSettings ) ) {
1042 self
::PARAM_DFLT
=> $paramSettings,
1046 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1047 ?
$paramSettings[self
::PARAM_DFLT
]
1049 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1050 ?
$paramSettings[self
::PARAM_ISMULTI
]
1052 $multiLimit1 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] )
1053 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT1
]
1055 $multiLimit2 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] )
1056 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT2
]
1058 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1059 ?
$paramSettings[self
::PARAM_TYPE
]
1061 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1062 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1064 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1065 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1067 $deprecatedValues = isset( $paramSettings[self
::PARAM_DEPRECATED_VALUES
] )
1068 ?
$paramSettings[self
::PARAM_DEPRECATED_VALUES
]
1070 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1071 ?
$paramSettings[self
::PARAM_REQUIRED
]
1073 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1074 ?
$paramSettings[self
::PARAM_ALL
]
1077 // When type is not given, and no choices, the type is the same as $default
1078 if ( !isset( $type ) ) {
1079 if ( isset( $default ) ) {
1080 $type = gettype( $default );
1082 $type = 'NULL'; // allow everything
1086 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1087 $this->getMain()->markParamsSensitive( $encParamName );
1090 if ( $type == 'boolean' ) {
1091 if ( isset( $default ) && $default !== false ) {
1092 // Having a default value of anything other than 'false' is not allowed
1095 "Boolean param $encParamName's default is set to '$default'. " .
1096 'Boolean parameters must default to false.'
1100 $value = $this->getMain()->getCheck( $encParamName );
1101 } elseif ( $type == 'upload' ) {
1102 if ( isset( $default ) ) {
1103 // Having a default value is not allowed
1106 "File upload param $encParamName's default is set to " .
1107 "'$default'. File upload parameters may not have a default." );
1110 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1112 $value = $this->getMain()->getUpload( $encParamName );
1113 if ( !$value->exists() ) {
1114 // This will get the value without trying to normalize it
1115 // (because trying to normalize a large binary file
1116 // accidentally uploaded as a field fails spectacularly)
1117 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1118 if ( $value !== null ) {
1119 $this->dieWithError(
1120 [ 'apierror-badupload', $encParamName ],
1121 "badupload_{$encParamName}"
1126 $value = $this->getMain()->getVal( $encParamName, $default );
1128 if ( isset( $value ) && $type == 'namespace' ) {
1129 $type = MWNamespace
::getValidNamespaces();
1130 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1131 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1133 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1135 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1139 if ( isset( $value ) && $type == 'submodule' ) {
1140 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1141 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1143 $type = $this->getModuleManager()->getNames( $paramName );
1147 $request = $this->getMain()->getRequest();
1148 $rawValue = $request->getRawVal( $encParamName );
1149 if ( $rawValue === null ) {
1150 $rawValue = $default;
1153 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1154 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1156 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1157 // done by WebRequest for $_GET. Let's call that a feature.
1158 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1160 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1164 // Check for NFC normalization, and warn
1165 if ( $rawValue !== $value ) {
1166 $this->handleParamNormalization( $paramName, $value, $rawValue );
1170 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1171 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1174 "For param $encParamName, PARAM_ALL collides with a possible value" );
1176 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1177 $value = $this->parseMultiValue(
1181 is_array( $type ) ?
$type : null,
1182 $allowAll ?
$allSpecifier : null,
1188 if ( isset( $value ) ) {
1189 // More validation only when choices were not given
1190 // choices were validated in parseMultiValue()
1191 if ( !is_array( $type ) ) {
1193 case 'NULL': // nothing to do
1198 if ( $required && $value === '' ) {
1199 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1202 case 'integer': // Force everything using intval() and optionally validate limits
1203 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1204 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1205 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1206 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1208 if ( is_array( $value ) ) {
1209 $value = array_map( 'intval', $value );
1210 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1211 foreach ( $value as &$v ) {
1212 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1216 $value = intval( $value );
1217 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1218 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1223 if ( !$parseLimit ) {
1224 // Don't do any validation whatsoever
1227 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1228 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1232 "MAX1 or MAX2 are not defined for the limit $encParamName"
1236 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1238 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1239 if ( $value == 'max' ) {
1240 $value = $this->getMain()->canApiHighLimits()
1241 ?
$paramSettings[self
::PARAM_MAX2
]
1242 : $paramSettings[self
::PARAM_MAX
];
1243 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1245 $value = intval( $value );
1246 $this->validateLimit(
1250 $paramSettings[self
::PARAM_MAX
],
1251 $paramSettings[self
::PARAM_MAX2
]
1257 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1261 if ( is_array( $value ) ) {
1262 foreach ( $value as $key => $val ) {
1263 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1266 $value = $this->validateTimestamp( $value, $encParamName );
1270 if ( is_array( $value ) ) {
1271 foreach ( $value as $key => $val ) {
1272 $value[$key] = $this->validateUser( $val, $encParamName );
1275 $value = $this->validateUser( $value, $encParamName );
1278 case 'upload': // nothing to do
1281 // If change tagging was requested, check that the tags are valid.
1282 if ( !is_array( $value ) && !$multi ) {
1283 $value = [ $value ];
1285 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1286 if ( !$tagsStatus->isGood() ) {
1287 $this->dieStatus( $tagsStatus );
1291 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1295 // Throw out duplicates if requested
1296 if ( !$dupes && is_array( $value ) ) {
1297 $value = array_unique( $value );
1300 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1301 foreach ( (array)$value as $val ) {
1302 if ( isset( $paramSettings[self
::PARAM_MAX_BYTES
] )
1303 && strlen( $val ) > $paramSettings[self
::PARAM_MAX_BYTES
]
1305 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1306 $paramSettings[self
::PARAM_MAX_BYTES
] ] );
1308 if ( isset( $paramSettings[self
::PARAM_MAX_CHARS
] )
1309 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self
::PARAM_MAX_CHARS
]
1311 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1312 $paramSettings[self
::PARAM_MAX_CHARS
] ] );
1317 // Set a warning if a deprecated parameter has been passed
1318 if ( $deprecated && $value !== false ) {
1319 $feature = $encParamName;
1321 while ( !$m->isMain() ) {
1322 $p = $m->getParent();
1323 $name = $m->getModuleName();
1324 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1325 $feature = "{$param}={$name}&{$feature}";
1328 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1331 // Set a warning if a deprecated parameter value has been passed
1332 $usedDeprecatedValues = $deprecatedValues && $value !== false
1333 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1335 if ( $usedDeprecatedValues ) {
1336 $feature = "$encParamName=";
1338 while ( !$m->isMain() ) {
1339 $p = $m->getParent();
1340 $name = $m->getModuleName();
1341 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1342 $feature = "{$param}={$name}&{$feature}";
1345 foreach ( $usedDeprecatedValues as $v ) {
1346 $msg = $deprecatedValues[$v];
1347 if ( $msg === true ) {
1348 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1350 $this->addDeprecation( $msg, "$feature$v" );
1353 } elseif ( $required ) {
1354 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1361 * Handle when a parameter was Unicode-normalized
1363 * @param string $paramName Unprefixed parameter name
1364 * @param string $value Input that will be used.
1365 * @param string $rawValue Input before normalization.
1367 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1368 $encParamName = $this->encodeParamName( $paramName );
1369 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1373 * Split a multi-valued parameter string, like explode()
1375 * @param string $value
1379 protected function explodeMultiValue( $value, $limit ) {
1380 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1382 $value = substr( $value, 1 );
1387 return explode( $sep, $value, $limit );
1391 * Return an array of values that were given in a 'a|b|c' notation,
1392 * after it optionally validates them against the list allowed values.
1394 * @param string $valueName The name of the parameter (for error
1396 * @param mixed $value The value being parsed
1397 * @param bool $allowMultiple Can $value contain more than one value
1399 * @param string[]|null $allowedValues An array of values to check against. If
1400 * null, all values are accepted.
1401 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1402 * if this behavior should not be allowed
1403 * @param int|null $limit1 Maximum number of values, for normal users.
1404 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1405 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1407 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1408 $allSpecifier = null, $limit1 = null, $limit2 = null
1410 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1413 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1414 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1416 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1417 // because it unstubs $wgUser
1418 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1419 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1423 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1424 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1426 return $allowedValues;
1429 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1430 $this->addDeprecation(
1431 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1432 "too-many-$valueName-for-{$this->getModulePath()}"
1436 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1437 // T35482 - Allow entries with | in them for non-multiple values
1438 if ( in_array( $value, $allowedValues, true ) ) {
1442 if ( is_array( $allowedValues ) ) {
1443 $values = array_map( function ( $v ) {
1444 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1445 }, $allowedValues );
1446 $this->dieWithError( [
1447 'apierror-multival-only-one-of',
1449 Message
::listParam( $values ),
1451 ], "multival_$valueName" );
1453 $this->dieWithError( [
1454 'apierror-multival-only-one',
1456 ], "multival_$valueName" );
1460 if ( is_array( $allowedValues ) ) {
1461 // Check for unknown values
1462 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1463 if ( count( $unknown ) ) {
1464 if ( $allowMultiple ) {
1465 $this->addWarning( [
1466 'apiwarn-unrecognizedvalues',
1468 Message
::listParam( $unknown, 'comma' ),
1472 $this->dieWithError(
1473 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1474 "unknown_$valueName"
1478 // Now throw them out
1479 $valuesList = array_intersect( $valuesList, $allowedValues );
1482 return $allowMultiple ?
$valuesList : $valuesList[0];
1486 * Validate the value against the minimum and user/bot maximum limits.
1487 * Prints usage info on failure.
1488 * @param string $paramName Parameter name
1489 * @param int &$value Parameter value
1490 * @param int|null $min Minimum value
1491 * @param int|null $max Maximum value for users
1492 * @param int $botMax Maximum value for sysops/bots
1493 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1495 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1496 $enforceLimits = false
1498 if ( !is_null( $min ) && $value < $min ) {
1499 $msg = ApiMessage
::create(
1500 [ 'apierror-integeroutofrange-belowminimum',
1501 $this->encodeParamName( $paramName ), $min, $value ],
1502 'integeroutofrange',
1503 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1505 $this->warnOrDie( $msg, $enforceLimits );
1509 // Minimum is always validated, whereas maximum is checked only if not
1510 // running in internal call mode
1511 if ( $this->getMain()->isInternalMode() ) {
1515 // Optimization: do not check user's bot status unless really needed -- skips db query
1516 // assumes $botMax >= $max
1517 if ( !is_null( $max ) && $value > $max ) {
1518 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1519 if ( $value > $botMax ) {
1520 $msg = ApiMessage
::create(
1521 [ 'apierror-integeroutofrange-abovebotmax',
1522 $this->encodeParamName( $paramName ), $botMax, $value ],
1523 'integeroutofrange',
1524 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1526 $this->warnOrDie( $msg, $enforceLimits );
1530 $msg = ApiMessage
::create(
1531 [ 'apierror-integeroutofrange-abovemax',
1532 $this->encodeParamName( $paramName ), $max, $value ],
1533 'integeroutofrange',
1534 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1536 $this->warnOrDie( $msg, $enforceLimits );
1543 * Validate and normalize of parameters of type 'timestamp'
1544 * @param string $value Parameter value
1545 * @param string $encParamName Parameter name
1546 * @return string Validated and normalized parameter
1548 protected function validateTimestamp( $value, $encParamName ) {
1549 // Confusing synonyms for the current time accepted by wfTimestamp()
1550 // (wfTimestamp() also accepts various non-strings and the string of 14
1551 // ASCII NUL bytes, but those can't get here)
1553 $this->addDeprecation(
1554 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1555 'unclear-"now"-timestamp'
1557 return wfTimestamp( TS_MW
);
1560 // Explicit synonym for the current time
1561 if ( $value === 'now' ) {
1562 return wfTimestamp( TS_MW
);
1565 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1566 if ( $unixTimestamp === false ) {
1567 $this->dieWithError(
1568 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1569 "badtimestamp_{$encParamName}"
1573 return wfTimestamp( TS_MW
, $unixTimestamp );
1577 * Validate the supplied token.
1580 * @param string $token Supplied token
1581 * @param array $params All supplied parameters for the module
1583 * @throws MWException
1585 final public function validateToken( $token, array $params ) {
1586 $tokenType = $this->needsToken();
1587 $salts = ApiQueryTokens
::getTokenTypeSalts();
1588 if ( !isset( $salts[$tokenType] ) ) {
1589 throw new MWException(
1590 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1591 'without registering it'
1595 $tokenObj = ApiQueryTokens
::getToken(
1596 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1598 if ( $tokenObj->match( $token ) ) {
1602 $webUiSalt = $this->getWebUITokenSalt( $params );
1603 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1615 * Validate and normalize of parameters of type 'user'
1616 * @param string $value Parameter value
1617 * @param string $encParamName Parameter name
1618 * @return string Validated and normalized parameter
1620 private function validateUser( $value, $encParamName ) {
1621 $title = Title
::makeTitleSafe( NS_USER
, $value );
1622 if ( $title === null ||
$title->hasFragment() ) {
1623 $this->dieWithError(
1624 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1625 "baduser_{$encParamName}"
1629 return $title->getText();
1634 /************************************************************************//**
1635 * @name Utility methods
1640 * Set a watch (or unwatch) based the based on a watchlist parameter.
1641 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1642 * @param Title $titleObj The article's title to change
1643 * @param string $userOption The user option to consider when $watch=preferences
1645 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1646 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1647 if ( $value === null ) {
1651 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1655 * Truncate an array to a certain length.
1656 * @param array &$arr Array to truncate
1657 * @param int $limit Maximum length
1658 * @return bool True if the array was truncated, false otherwise
1660 public static function truncateArray( &$arr, $limit ) {
1662 while ( count( $arr ) > $limit ) {
1671 * Gets the user for whom to get the watchlist
1673 * @param array $params
1676 public function getWatchlistUser( $params ) {
1677 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1678 $user = User
::newFromName( $params['owner'], false );
1679 if ( !( $user && $user->getId() ) ) {
1680 $this->dieWithError(
1681 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1684 $token = $user->getOption( 'watchlisttoken' );
1685 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1686 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1689 if ( !$this->getUser()->isLoggedIn() ) {
1690 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1692 $this->checkUserRightsAny( 'viewmywatchlist' );
1693 $user = $this->getUser();
1700 * A subset of wfEscapeWikiText for BC texts
1703 * @param string|array $v
1704 * @return string|array
1706 private static function escapeWikiText( $v ) {
1707 if ( is_array( $v ) ) {
1708 return array_map( 'self::escapeWikiText', $v );
1711 '__' => '__', '{' => '{', '}' => '}',
1712 '[[Category:' => '[[:Category:',
1713 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1719 * Create a Message from a string or array
1721 * A string is used as a message key. An array has the message key as the
1722 * first value and message parameters as subsequent values.
1725 * @param string|array|Message $msg
1726 * @param IContextSource $context
1727 * @param array $params
1728 * @return Message|null
1730 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1731 if ( is_string( $msg ) ) {
1732 $msg = wfMessage( $msg );
1733 } elseif ( is_array( $msg ) ) {
1734 $msg = call_user_func_array( 'wfMessage', $msg );
1736 if ( !$msg instanceof Message
) {
1740 $msg->setContext( $context );
1742 $msg->params( $params );
1749 * Turn an array of message keys or key+param arrays into a Status
1751 * @param array $errors
1752 * @param User|null $user
1755 public function errorArrayToStatus( array $errors, User
$user = null ) {
1756 if ( $user === null ) {
1757 $user = $this->getUser();
1760 $status = Status
::newGood();
1761 foreach ( $errors as $error ) {
1762 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1763 $status->fatal( ApiMessage
::create(
1766 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1768 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1769 $status->fatal( ApiMessage
::create(
1770 'apierror-autoblocked',
1772 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1774 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1775 $status->fatal( ApiMessage
::create(
1776 'apierror-systemblocked',
1778 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1781 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1789 /************************************************************************//**
1790 * @name Warning and error reporting
1795 * Add a warning for this module.
1797 * Users should monitor this section to notice any changes in API. Multiple
1798 * calls to this function will result in multiple warning messages.
1800 * If $msg is not an ApiMessage, the message code will be derived from the
1801 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1804 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1805 * @param string|null $code See ApiErrorFormatter::addWarning()
1806 * @param array|null $data See ApiErrorFormatter::addWarning()
1808 public function addWarning( $msg, $code = null, $data = null ) {
1809 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1813 * Add a deprecation warning for this module.
1815 * A combination of $this->addWarning() and $this->logFeatureUsage()
1818 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1819 * @param string|null $feature See ApiBase::logFeatureUsage()
1820 * @param array|null $data See ApiErrorFormatter::addWarning()
1822 public function addDeprecation( $msg, $feature, $data = [] ) {
1823 $data = (array)$data;
1824 if ( $feature !== null ) {
1825 $data['feature'] = $feature;
1826 $this->logFeatureUsage( $feature );
1828 $this->addWarning( $msg, 'deprecation', $data );
1830 // No real need to deduplicate here, ApiErrorFormatter does that for
1831 // us (assuming the hook is deterministic).
1832 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1833 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1834 if ( count( $msgs ) > 1 ) {
1835 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1836 $msg = ( new RawMessage( $key ) )->params( $msgs );
1838 $msg = reset( $msgs );
1840 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1844 * Add an error for this module without aborting
1846 * If $msg is not an ApiMessage, the message code will be derived from the
1847 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1849 * @note If you want to abort processing, use self::dieWithError() instead.
1851 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1852 * @param string|null $code See ApiErrorFormatter::addError()
1853 * @param array|null $data See ApiErrorFormatter::addError()
1855 public function addError( $msg, $code = null, $data = null ) {
1856 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1860 * Add warnings and/or errors from a Status
1862 * @note If you want to abort processing, use self::dieStatus() instead.
1864 * @param StatusValue $status
1865 * @param string[] $types 'warning' and/or 'error'
1867 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1868 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1872 * Abort execution with an error
1874 * If $msg is not an ApiMessage, the message code will be derived from the
1875 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1878 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1879 * @param string|null $code See ApiErrorFormatter::addError()
1880 * @param array|null $data See ApiErrorFormatter::addError()
1881 * @param int|null $httpCode HTTP error code to use
1882 * @throws ApiUsageException always
1884 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1885 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1889 * Abort execution with an error derived from an exception
1892 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1893 * @param array $options See ApiErrorFormatter::getMessageFromException()
1894 * @throws ApiUsageException always
1896 public function dieWithException( $exception, array $options = [] ) {
1897 $this->dieWithError(
1898 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1903 * Adds a warning to the output, else dies
1905 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1906 * @param bool $enforceLimits Whether this is an enforce (die)
1908 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1909 if ( $enforceLimits ) {
1910 $this->dieWithError( $msg );
1912 $this->addWarning( $msg );
1917 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1918 * error handler and die with an error message including block info.
1921 * @param Block $block The block used to generate the ApiUsageException
1922 * @throws ApiUsageException always
1924 public function dieBlocked( Block
$block ) {
1925 // Die using the appropriate message depending on block type
1926 if ( $block->getType() == Block
::TYPE_AUTO
) {
1927 $this->dieWithError(
1928 'apierror-autoblocked',
1930 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1933 $this->dieWithError(
1936 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1942 * Throw an ApiUsageException based on the Status object.
1945 * @since 1.29 Accepts a StatusValue
1946 * @param StatusValue $status
1947 * @throws ApiUsageException always
1949 public function dieStatus( StatusValue
$status ) {
1950 if ( $status->isGood() ) {
1951 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1954 // ApiUsageException needs a fatal status, but this method has
1955 // historically accepted any non-good status. Convert it if necessary.
1956 $status->setOK( false );
1957 if ( !$status->getErrorsByType( 'error' ) ) {
1958 $newStatus = Status
::newGood();
1959 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1960 call_user_func_array(
1961 [ $newStatus, 'fatal' ],
1962 array_merge( [ $err['message'] ], $err['params'] )
1965 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1966 $newStatus->fatal( 'unknownerror-nocode' );
1968 $status = $newStatus;
1971 throw new ApiUsageException( $this, $status );
1975 * Helper function for readonly errors
1977 * @throws ApiUsageException always
1979 public function dieReadOnly() {
1980 $this->dieWithError(
1981 'apierror-readonly',
1983 [ 'readonlyreason' => wfReadOnlyReason() ]
1988 * Helper function for permission-denied errors
1990 * @param string|string[] $rights
1991 * @param User|null $user
1992 * @throws ApiUsageException if the user doesn't have any of the rights.
1993 * The error message is based on $rights[0].
1995 public function checkUserRightsAny( $rights, $user = null ) {
1997 $user = $this->getUser();
1999 $rights = (array)$rights;
2000 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
2001 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2006 * Helper function for permission-denied errors
2008 * @param Title $title
2009 * @param string|string[] $actions
2010 * @param User|null $user
2011 * @throws ApiUsageException if the user doesn't have all of the rights.
2013 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
2015 $user = $this->getUser();
2019 foreach ( (array)$actions as $action ) {
2020 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2023 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2028 * Will only set a warning instead of failing if the global $wgDebugAPI
2029 * is set to true. Otherwise behaves exactly as self::dieWithError().
2032 * @param string|array|Message $msg
2033 * @param string|null $code
2034 * @param array|null $data
2035 * @param int|null $httpCode
2036 * @throws ApiUsageException
2038 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2039 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2040 $this->dieWithError( $msg, $code, $data, $httpCode );
2042 $this->addWarning( $msg, $code, $data );
2047 * Die with the 'badcontinue' error.
2049 * This call is common enough to make it into the base method.
2051 * @param bool $condition Will only die if this value is true
2052 * @throws ApiUsageException
2055 protected function dieContinueUsageIf( $condition ) {
2057 $this->dieWithError( 'apierror-badcontinue' );
2062 * Internal code errors should be reported with this method
2063 * @param string $method Method or function name
2064 * @param string $message Error message
2065 * @throws MWException always
2067 protected static function dieDebug( $method, $message ) {
2068 throw new MWException( "Internal error in $method: $message" );
2072 * Write logging information for API features to a debug log, for usage
2074 * @note Consider using $this->addDeprecation() instead to both warn and log.
2075 * @param string $feature Feature being used.
2077 public function logFeatureUsage( $feature ) {
2078 $request = $this->getRequest();
2079 $s = '"' . addslashes( $feature ) . '"' .
2080 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2081 ' "' . $request->getIP() . '"' .
2082 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2083 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2084 wfDebugLog( 'api-feature-usage', $s, 'private' );
2089 /************************************************************************//**
2090 * @name Help message generation
2095 * Return the summary message.
2097 * This is a one-line description of the module, suitable for display in a
2101 * @return string|array|Message
2103 protected function getSummaryMessage() {
2104 return "apihelp-{$this->getModulePath()}-summary";
2108 * Return the extended help text message.
2110 * This is additional text to display at the top of the help section, below
2114 * @return string|array|Message
2116 protected function getExtendedDescription() {
2118 "apihelp-{$this->getModulePath()}-extended-description",
2119 'api-help-no-extended-description',
2124 * Get final module summary
2126 * Ideally this will just be the getSummaryMessage(). However, for
2127 * backwards compatibility, if that message does not exist then the first
2128 * line of wikitext from the description message will be used instead.
2133 public function getFinalSummary() {
2134 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2135 $this->getModulePrefix(),
2136 $this->getModuleName(),
2137 $this->getModulePath(),
2139 if ( !$msg->exists() ) {
2140 wfDeprecated( 'API help "description" messages', '1.30' );
2141 $msg = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2142 $this->getModulePrefix(),
2143 $this->getModuleName(),
2144 $this->getModulePath(),
2146 $msg = self
::makeMessage( 'rawmessage', $this->getContext(), [
2147 preg_replace( '/\n.*/s', '', $msg->text() )
2154 * Get final module description, after hooks have had a chance to tweak it as
2157 * @since 1.25, returns Message[] rather than string[]
2160 public function getFinalDescription() {
2161 $desc = $this->getDescription();
2163 // Avoid PHP 7.1 warning of passing $this by reference
2165 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2166 $desc = self
::escapeWikiText( $desc );
2167 if ( is_array( $desc ) ) {
2168 $desc = implode( "\n", $desc );
2170 $desc = (string)$desc;
2173 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2174 $this->getModulePrefix(),
2175 $this->getModuleName(),
2176 $this->getModulePath(),
2178 $extendedDescription = self
::makeMessage(
2179 $this->getExtendedDescription(), $this->getContext(), [
2180 $this->getModulePrefix(),
2181 $this->getModuleName(),
2182 $this->getModulePath(),
2186 if ( $summary->exists() ) {
2187 $msgs = [ $summary, $extendedDescription ];
2189 wfDeprecated( 'API help "description" messages', '1.30' );
2190 $description = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2191 $this->getModulePrefix(),
2192 $this->getModuleName(),
2193 $this->getModulePath(),
2195 if ( !$description->exists() ) {
2196 $description = $this->msg( 'api-help-fallback-description', $desc );
2198 $msgs = [ $description ];
2201 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2207 * Get final list of parameters, after hooks have had a chance to
2208 * tweak it as needed.
2210 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2211 * @return array|bool False on no parameters
2212 * @since 1.21 $flags param added
2214 public function getFinalParams( $flags = 0 ) {
2215 $params = $this->getAllowedParams( $flags );
2220 if ( $this->needsToken() ) {
2221 $params['token'] = [
2222 self
::PARAM_TYPE
=> 'string',
2223 self
::PARAM_REQUIRED
=> true,
2224 self
::PARAM_SENSITIVE
=> true,
2225 self
::PARAM_HELP_MSG
=> [
2226 'api-help-param-token',
2227 $this->needsToken(),
2229 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2232 // Avoid PHP 7.1 warning of passing $this by reference
2234 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2240 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2243 * @since 1.25, returns array of Message[] rather than array of string[]
2244 * @return array Keys are parameter names, values are arrays of Message objects
2246 public function getFinalParamDescription() {
2247 $prefix = $this->getModulePrefix();
2248 $name = $this->getModuleName();
2249 $path = $this->getModulePath();
2251 $desc = $this->getParamDescription();
2253 // Avoid PHP 7.1 warning of passing $this by reference
2255 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2260 $desc = self
::escapeWikiText( $desc );
2262 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2264 foreach ( $params as $param => $settings ) {
2265 if ( !is_array( $settings ) ) {
2269 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2270 if ( is_array( $d ) ) {
2271 // Special handling for prop parameters
2272 $d = array_map( function ( $line ) {
2273 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2274 $line = "\n;{$m[1]}:{$m[2]}";
2278 $d = implode( ' ', $d );
2281 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2282 $msg = $settings[self
::PARAM_HELP_MSG
];
2284 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2285 if ( !$msg->exists() ) {
2286 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2289 $msg = self
::makeMessage( $msg, $this->getContext(),
2290 [ $prefix, $param, $name, $path ] );
2292 self
::dieDebug( __METHOD__
,
2293 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2295 $msgs[$param] = [ $msg ];
2297 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2298 $settings[self
::PARAM_TYPE
] === 'submodule'
2300 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2301 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2303 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2305 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2306 $map[$submoduleName] = $prefix . $submoduleName;
2311 $deprecatedSubmodules = [];
2312 foreach ( $map as $v => $m ) {
2313 $arr = &$submodules;
2314 $isDeprecated = false;
2317 $submod = $this->getModuleFromPath( $m );
2319 $summary = $submod->getFinalSummary();
2320 $isDeprecated = $submod->isDeprecated();
2321 if ( $isDeprecated ) {
2322 $arr = &$deprecatedSubmodules;
2325 } catch ( ApiUsageException
$ex ) {
2329 $key = $summary->getKey();
2330 $params = $summary->getParams();
2332 $key = 'api-help-undocumented-module';
2335 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2336 $arr[] = $m->setContext( $this->getContext() );
2338 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2339 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2340 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2341 self
::dieDebug( __METHOD__
,
2342 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2344 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2345 self
::dieDebug( __METHOD__
,
2346 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2347 'ApiBase::PARAM_TYPE is an array' );
2350 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2351 $deprecatedValues = isset( $settings[self
::PARAM_DEPRECATED_VALUES
] )
2352 ?
$settings[self
::PARAM_DEPRECATED_VALUES
]
2355 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2356 if ( isset( $valueMsgs[$value] ) ) {
2357 $msg = $valueMsgs[$value];
2359 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2361 $m = self
::makeMessage( $msg, $this->getContext(),
2362 [ $prefix, $param, $name, $path, $value ] );
2364 $m = new ApiHelpParamValueMessage(
2366 [ $m->getKey(), 'api-help-param-no-description' ],
2368 isset( $deprecatedValues[$value] )
2370 $msgs[$param][] = $m->setContext( $this->getContext() );
2372 self
::dieDebug( __METHOD__
,
2373 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2378 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2379 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2380 self
::dieDebug( __METHOD__
,
2381 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2383 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2384 $m = self
::makeMessage( $m, $this->getContext(),
2385 [ $prefix, $param, $name, $path ] );
2387 $msgs[$param][] = $m;
2389 self
::dieDebug( __METHOD__
,
2390 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2396 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2402 * Generates the list of flags for the help screen and for action=paraminfo
2404 * Corresponding messages: api-help-flag-deprecated,
2405 * api-help-flag-internal, api-help-flag-readrights,
2406 * api-help-flag-writerights, api-help-flag-mustbeposted
2410 protected function getHelpFlags() {
2413 if ( $this->isDeprecated() ) {
2414 $flags[] = 'deprecated';
2416 if ( $this->isInternal() ) {
2417 $flags[] = 'internal';
2419 if ( $this->isReadMode() ) {
2420 $flags[] = 'readrights';
2422 if ( $this->isWriteMode() ) {
2423 $flags[] = 'writerights';
2425 if ( $this->mustBePosted() ) {
2426 $flags[] = 'mustbeposted';
2433 * Returns information about the source of this module, if known
2435 * Returned array is an array with the following keys:
2436 * - path: Install path
2437 * - name: Extension name, or "MediaWiki" for core
2438 * - namemsg: (optional) i18n message key for a display name
2439 * - license-name: (optional) Name of license
2441 * @return array|null
2443 protected function getModuleSourceInfo() {
2446 if ( $this->mModuleSource
!== false ) {
2447 return $this->mModuleSource
;
2450 // First, try to find where the module comes from...
2451 $rClass = new ReflectionClass( $this );
2452 $path = $rClass->getFileName();
2455 $this->mModuleSource
= null;
2458 $path = realpath( $path ) ?
: $path;
2460 // Build map of extension directories to extension info
2461 if ( self
::$extensionInfo === null ) {
2462 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2463 self
::$extensionInfo = [
2464 realpath( __DIR__
) ?
: __DIR__
=> [
2466 'name' => 'MediaWiki',
2467 'license-name' => 'GPL-2.0+',
2469 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2470 realpath( $extDir ) ?
: $extDir => null,
2476 'license-name' => null,
2478 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2479 foreach ( $group as $ext ) {
2480 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2481 // This shouldn't happen, but does anyway.
2485 $extpath = $ext['path'];
2486 if ( !is_dir( $extpath ) ) {
2487 $extpath = dirname( $extpath );
2489 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2490 array_intersect_key( $ext, $keep );
2493 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2494 $extpath = $ext['path'];
2495 if ( !is_dir( $extpath ) ) {
2496 $extpath = dirname( $extpath );
2498 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2499 array_intersect_key( $ext, $keep );
2503 // Now traverse parent directories until we find a match or run out of
2506 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2508 $this->mModuleSource
= self
::$extensionInfo[$path];
2509 return $this->mModuleSource
;
2513 $path = dirname( $path );
2514 } while ( $path !== $oldpath );
2516 // No idea what extension this might be.
2517 $this->mModuleSource
= null;
2522 * Called from ApiHelp before the pieces are joined together and returned.
2524 * This exists mainly for ApiMain to add the Permissions and Credits
2525 * sections. Other modules probably don't need it.
2527 * @param string[] &$help Array of help data
2528 * @param array $options Options passed to ApiHelp::getHelp
2529 * @param array &$tocData If a TOC is being generated, this array has keys
2530 * as anchors in the page and values as for Linker::generateTOC().
2532 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2537 /************************************************************************//**
2543 * Returns the description string for this module
2545 * Ignored if an i18n message exists for
2546 * "apihelp-{$this->getModulePath()}-description".
2548 * @deprecated since 1.25
2549 * @return Message|string|array|false
2551 protected function getDescription() {
2556 * Returns an array of parameter descriptions.
2558 * For each parameter, ignored if an i18n message exists for the parameter.
2559 * By default that message is
2560 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2561 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2562 * self::getFinalParams().
2564 * @deprecated since 1.25
2565 * @return array|bool False on no parameter descriptions
2567 protected function getParamDescription() {
2572 * Returns usage examples for this module.
2574 * Return value as an array is either:
2575 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2577 * - sequential numeric keys with even-numbered keys being display-text
2578 * and odd-numbered keys being partial urls
2579 * - partial URLs as keys with display-text (string or array-to-be-joined)
2581 * Return value as a string is the same as an array with a numeric key and
2582 * that value, and boolean false means "no examples".
2584 * @deprecated since 1.25, use getExamplesMessages() instead
2585 * @return bool|string|array
2587 protected function getExamples() {
2592 * @deprecated since 1.25, always returns empty string
2593 * @param IDatabase|bool $db
2596 public function getModuleProfileName( $db = false ) {
2597 wfDeprecated( __METHOD__
, '1.25' );
2602 * @deprecated since 1.25
2604 public function profileIn() {
2605 // No wfDeprecated() yet because extensions call this and might need to
2606 // keep doing so for BC.
2610 * @deprecated since 1.25
2612 public function profileOut() {
2613 // No wfDeprecated() yet because extensions call this and might need to
2614 // keep doing so for BC.
2618 * @deprecated since 1.25
2620 public function safeProfileOut() {
2621 wfDeprecated( __METHOD__
, '1.25' );
2625 * @deprecated since 1.25, always returns 0
2628 public function getProfileTime() {
2629 wfDeprecated( __METHOD__
, '1.25' );
2634 * @deprecated since 1.25
2636 public function profileDBIn() {
2637 wfDeprecated( __METHOD__
, '1.25' );
2641 * @deprecated since 1.25
2643 public function profileDBOut() {
2644 wfDeprecated( __METHOD__
, '1.25' );
2648 * @deprecated since 1.25, always returns 0
2651 public function getProfileDBTime() {
2652 wfDeprecated( __METHOD__
, '1.25' );
2657 * Call wfTransactionalTimeLimit() if this request was POSTed
2660 protected function useTransactionalTimeLimit() {
2661 if ( $this->getRequest()->wasPosted() ) {
2662 wfTransactionalTimeLimit();
2667 * @deprecated since 1.29, use ApiBase::addWarning() instead
2668 * @param string $warning Warning message
2670 public function setWarning( $warning ) {
2671 wfDeprecated( __METHOD__
, '1.29' );
2672 $msg = new ApiRawMessage( $warning, 'warning' );
2673 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2677 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2678 * error handler and die with an error message.
2680 * @deprecated since 1.29, use self::dieWithError() instead
2681 * @param string $description One-line human-readable description of the
2682 * error condition, e.g., "The API requires a valid action parameter"
2683 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2684 * automated identification of the error, e.g., 'unknown_action'
2685 * @param int $httpRespCode HTTP response code
2686 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2687 * @throws ApiUsageException always
2689 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2690 wfDeprecated( __METHOD__
, '1.29' );
2691 $this->dieWithError(
2692 new RawMessage( '$1', [ $description ] ),
2700 * Get error (as code, string) from a Status object.
2703 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2704 * @param Status $status
2705 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2706 * @return array Array of code and error string
2707 * @throws MWException
2709 public function getErrorFromStatus( $status, &$extraData = null ) {
2710 wfDeprecated( __METHOD__
, '1.29' );
2711 if ( $status->isGood() ) {
2712 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2715 $errors = $status->getErrorsByType( 'error' );
2717 // No errors? Assume the warnings should be treated as errors
2718 $errors = $status->getErrorsByType( 'warning' );
2721 // Still no errors? Punt
2722 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2725 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2726 $msg = $errors[0]['message'];
2728 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2730 if ( !$msg instanceof IApiMessage
) {
2731 $key = $msg->getKey();
2732 $params = $msg->getParams();
2733 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2734 $msg = ApiMessage
::create( $params );
2739 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2744 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2745 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2746 * API codes and message texts, and a few interfaces required poking
2747 * something in here. Now we're repurposing it to map those same strings
2748 * to i18n messages, and declaring that any interface that requires poking
2749 * at this is broken and needs replacing ASAP.
2751 private static $messageMap = [
2752 'unknownerror' => 'apierror-unknownerror',
2753 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2754 'ns-specialprotected' => 'ns-specialprotected',
2755 'protectedinterface' => 'protectedinterface',
2756 'namespaceprotected' => 'namespaceprotected',
2757 'customcssprotected' => 'customcssprotected',
2758 'customjsprotected' => 'customjsprotected',
2759 'cascadeprotected' => 'cascadeprotected',
2760 'protectedpagetext' => 'protectedpagetext',
2761 'protect-cantedit' => 'protect-cantedit',
2762 'deleteprotected' => 'deleteprotected',
2763 'badaccess-group0' => 'badaccess-group0',
2764 'badaccess-groups' => 'badaccess-groups',
2765 'titleprotected' => 'titleprotected',
2766 'nocreate-loggedin' => 'nocreate-loggedin',
2767 'nocreatetext' => 'nocreatetext',
2768 'movenologintext' => 'movenologintext',
2769 'movenotallowed' => 'movenotallowed',
2770 'confirmedittext' => 'confirmedittext',
2771 'blockedtext' => 'apierror-blocked',
2772 'autoblockedtext' => 'apierror-autoblocked',
2773 'systemblockedtext' => 'apierror-systemblocked',
2774 'actionthrottledtext' => 'apierror-ratelimited',
2775 'alreadyrolled' => 'alreadyrolled',
2776 'cantrollback' => 'cantrollback',
2777 'readonlytext' => 'readonlytext',
2778 'sessionfailure' => 'sessionfailure',
2779 'cannotdelete' => 'cannotdelete',
2780 'notanarticle' => 'apierror-missingtitle',
2781 'selfmove' => 'selfmove',
2782 'immobile_namespace' => 'apierror-immobilenamespace',
2783 'articleexists' => 'articleexists',
2784 'hookaborted' => 'hookaborted',
2785 'cantmove-titleprotected' => 'cantmove-titleprotected',
2786 'imagenocrossnamespace' => 'imagenocrossnamespace',
2787 'imagetypemismatch' => 'imagetypemismatch',
2788 'ip_range_invalid' => 'ip_range_invalid',
2789 'range_block_disabled' => 'range_block_disabled',
2790 'nosuchusershort' => 'nosuchusershort',
2791 'badipaddress' => 'badipaddress',
2792 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2793 'ipb_already_blocked' => 'ipb_already_blocked',
2794 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2795 'ipb_cant_unblock' => 'ipb_cant_unblock',
2796 'mailnologin' => 'apierror-cantsend',
2797 'ipbblocked' => 'ipbblocked',
2798 'ipbnounblockself' => 'ipbnounblockself',
2799 'usermaildisabled' => 'usermaildisabled',
2800 'blockedemailuser' => 'apierror-blockedfrommail',
2801 'notarget' => 'apierror-notarget',
2802 'noemail' => 'noemail',
2803 'rcpatroldisabled' => 'rcpatroldisabled',
2804 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2805 'delete-toobig' => 'delete-toobig',
2806 'movenotallowedfile' => 'movenotallowedfile',
2807 'userrights-no-interwiki' => 'userrights-no-interwiki',
2808 'userrights-nodatabase' => 'userrights-nodatabase',
2809 'nouserspecified' => 'nouserspecified',
2810 'noname' => 'noname',
2811 'summaryrequired' => 'apierror-summaryrequired',
2812 'import-rootpage-invalid' => 'import-rootpage-invalid',
2813 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2814 'readrequired' => 'apierror-readapidenied',
2815 'writedisabled' => 'apierror-noapiwrite',
2816 'writerequired' => 'apierror-writeapidenied',
2817 'missingparam' => 'apierror-missingparam',
2818 'invalidtitle' => 'apierror-invalidtitle',
2819 'nosuchpageid' => 'apierror-nosuchpageid',
2820 'nosuchrevid' => 'apierror-nosuchrevid',
2821 'nosuchuser' => 'nosuchusershort',
2822 'invaliduser' => 'apierror-invaliduser',
2823 'invalidexpiry' => 'apierror-invalidexpiry',
2824 'pastexpiry' => 'apierror-pastexpiry',
2825 'create-titleexists' => 'apierror-create-titleexists',
2826 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2827 'cantblock' => 'apierror-cantblock',
2828 'canthide' => 'apierror-canthide',
2829 'cantblock-email' => 'apierror-cantblock-email',
2830 'cantunblock' => 'apierror-permissiondenied-generic',
2831 'cannotundelete' => 'cannotundelete',
2832 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2833 'createonly-exists' => 'apierror-articleexists',
2834 'nocreate-missing' => 'apierror-missingtitle',
2835 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2836 'nosuchrcid' => 'apierror-nosuchrcid',
2837 'nosuchlogid' => 'apierror-nosuchlogid',
2838 'protect-invalidaction' => 'apierror-protect-invalidaction',
2839 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2840 'toofewexpiries' => 'apierror-toofewexpiries',
2841 'cantimport' => 'apierror-cantimport',
2842 'cantimport-upload' => 'apierror-cantimport-upload',
2843 'importnofile' => 'importnofile',
2844 'importuploaderrorsize' => 'importuploaderrorsize',
2845 'importuploaderrorpartial' => 'importuploaderrorpartial',
2846 'importuploaderrortemp' => 'importuploaderrortemp',
2847 'importcantopen' => 'importcantopen',
2848 'import-noarticle' => 'import-noarticle',
2849 'importbadinterwiki' => 'importbadinterwiki',
2850 'import-unknownerror' => 'apierror-import-unknownerror',
2851 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2852 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2853 'mustbeposted' => 'apierror-mustbeposted',
2854 'show' => 'apierror-show',
2855 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2856 'invalidoldimage' => 'apierror-invalidoldimage',
2857 'nodeleteablefile' => 'apierror-nodeleteablefile',
2858 'fileexists-forbidden' => 'fileexists-forbidden',
2859 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2860 'filerevert-badversion' => 'filerevert-badversion',
2861 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2862 'noimageredirect-logged' => 'apierror-noimageredirect',
2863 'spamdetected' => 'apierror-spamdetected',
2864 'contenttoobig' => 'apierror-contenttoobig',
2865 'noedit-anon' => 'apierror-noedit-anon',
2866 'noedit' => 'apierror-noedit',
2867 'wasdeleted' => 'apierror-pagedeleted',
2868 'blankpage' => 'apierror-emptypage',
2869 'editconflict' => 'editconflict',
2870 'hashcheckfailed' => 'apierror-badmd5',
2871 'missingtext' => 'apierror-notext',
2872 'emptynewsection' => 'apierror-emptynewsection',
2873 'revwrongpage' => 'apierror-revwrongpage',
2874 'undo-failure' => 'undo-failure',
2875 'content-not-allowed-here' => 'content-not-allowed-here',
2876 'edit-hook-aborted' => 'edit-hook-aborted',
2877 'edit-gone-missing' => 'edit-gone-missing',
2878 'edit-conflict' => 'edit-conflict',
2879 'edit-already-exists' => 'edit-already-exists',
2880 'invalid-file-key' => 'apierror-invalid-file-key',
2881 'nouploadmodule' => 'apierror-nouploadmodule',
2882 'uploaddisabled' => 'uploaddisabled',
2883 'copyuploaddisabled' => 'copyuploaddisabled',
2884 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2885 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2886 'filename-tooshort' => 'filename-tooshort',
2887 'filename-toolong' => 'filename-toolong',
2888 'illegal-filename' => 'illegal-filename',
2889 'filetype-missing' => 'filetype-missing',
2890 'mustbeloggedin' => 'apierror-mustbeloggedin',
2894 * @deprecated do not use
2895 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2896 * @return ApiMessage
2898 private function parseMsgInternal( $error ) {
2899 $msg = Message
::newFromSpecifier( $error );
2900 if ( !$msg instanceof IApiMessage
) {
2901 $key = $msg->getKey();
2902 if ( isset( self
::$messageMap[$key] ) ) {
2903 $params = $msg->getParams();
2904 array_unshift( $params, self
::$messageMap[$key] );
2906 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2908 $msg = ApiMessage
::create( $params );
2914 * Return the error message related to a certain array
2915 * @deprecated since 1.29
2916 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2917 * @return array [ 'code' => code, 'info' => info ]
2919 public function parseMsg( $error ) {
2920 wfDeprecated( __METHOD__
, '1.29' );
2921 // Check whether someone passed the whole array, instead of one element as
2922 // documented. This breaks if it's actually an array of fallback keys, but
2923 // that's long-standing misbehavior introduced in r87627 to incorrectly
2925 if ( is_array( $error ) ) {
2926 $first = reset( $error );
2927 if ( is_array( $first ) ) {
2928 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2933 $msg = $this->parseMsgInternal( $error );
2935 'code' => $msg->getApiCode(),
2936 'info' => ApiErrorFormatter
::stripMarkup(
2937 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2939 'data' => $msg->getApiData()
2944 * Output the error message related to a certain array
2945 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2946 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2947 * @throws ApiUsageException always
2949 public function dieUsageMsg( $error ) {
2950 wfDeprecated( __METHOD__
, '1.29' );
2951 $this->dieWithError( $this->parseMsgInternal( $error ) );
2955 * Will only set a warning instead of failing if the global $wgDebugAPI
2956 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2957 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2958 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2959 * @throws ApiUsageException
2962 public function dieUsageMsgOrDebug( $error ) {
2963 wfDeprecated( __METHOD__
, '1.29' );
2964 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2968 * Return the description message.
2970 * This is additional text to display on the help page after the summary.
2972 * @deprecated since 1.30
2973 * @return string|array|Message
2975 protected function getDescriptionMessage() {
2977 "apihelp-{$this->getModulePath()}-description",
2978 "apihelp-{$this->getModulePath()}-summary",
2986 * For really cool vim folding this needs to be at the end:
2987 * vim: foldmarker=@{,@} foldmethod=marker