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;
222 const ALL_DEFAULT_STRING
= '*';
224 /** Fast query, standard limit. */
225 const LIMIT_BIG1
= 500;
226 /** Fast query, apihighlimits limit. */
227 const LIMIT_BIG2
= 5000;
228 /** Slow query, standard limit. */
229 const LIMIT_SML1
= 50;
230 /** Slow query, apihighlimits limit. */
231 const LIMIT_SML2
= 500;
234 * getAllowedParams() flag: When set, the result could take longer to generate,
235 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
238 const GET_VALUES_FOR_HELP
= 1;
240 /** @var array Maps extension paths to info arrays */
241 private static $extensionInfo = null;
244 private $mMainModule;
246 private $mModuleName, $mModulePrefix;
247 private $mSlaveDB = null;
248 private $mParamCache = [];
249 /** @var array|null|bool */
250 private $mModuleSource = false;
253 * @param ApiMain $mainModule
254 * @param string $moduleName Name of this module
255 * @param string $modulePrefix Prefix to use for parameter names
257 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
258 $this->mMainModule
= $mainModule;
259 $this->mModuleName
= $moduleName;
260 $this->mModulePrefix
= $modulePrefix;
262 if ( !$this->isMain() ) {
263 $this->setContext( $mainModule->getContext() );
267 /************************************************************************//**
268 * @name Methods to implement
273 * Evaluates the parameters, performs the requested query, and sets up
274 * the result. Concrete implementations of ApiBase must override this
275 * method to provide whatever functionality their module offers.
276 * Implementations must not produce any output on their own and are not
277 * expected to handle any errors.
279 * The execute() method will be invoked directly by ApiMain immediately
280 * before the result of the module is output. Aside from the
281 * constructor, implementations should assume that no other methods
282 * will be called externally on the module before the result is
285 * The result data should be stored in the ApiResult object available
286 * through getResult().
288 abstract public function execute();
291 * Get the module manager, or null if this module has no sub-modules
293 * @return ApiModuleManager
295 public function getModuleManager() {
300 * If the module may only be used with a certain format module,
301 * it should override this method to return an instance of that formatter.
302 * A value of null means the default format will be used.
303 * @note Do not use this just because you don't want to support non-json
304 * formats. This should be used only when there is a fundamental
305 * requirement for a specific format.
306 * @return mixed Instance of a derived class of ApiFormatBase, or null
308 public function getCustomPrinter() {
313 * Returns usage examples for this module.
315 * Return value has query strings as keys, with values being either strings
316 * (message key), arrays (message key + parameter), or Message objects.
318 * Do not call this base class implementation when overriding this method.
323 protected function getExamplesMessages() {
324 // Fall back to old non-localised method
327 $examples = $this->getExamples();
329 if ( !is_array( $examples ) ) {
330 $examples = [ $examples ];
331 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
332 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
333 !preg_match( '/^\s*api\.php\?/', $examples[0] )
335 // Fix up the ugly "even numbered elements are description, odd
336 // numbered elemts are the link" format (see doc for self::getExamples)
338 $examplesCount = count( $examples );
339 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
340 $tmp[$examples[$i +
1]] = $examples[$i];
345 foreach ( $examples as $k => $v ) {
346 if ( is_numeric( $k ) ) {
351 $msg = self
::escapeWikiText( $v );
352 if ( is_array( $msg ) ) {
353 $msg = implode( ' ', $msg );
357 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
358 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
366 * Return links to more detailed help pages about the module.
367 * @since 1.25, returning boolean false is deprecated
368 * @return string|array
370 public function getHelpUrls() {
375 * Returns an array of allowed parameters (parameter name) => (default
376 * value) or (parameter name) => (array with PARAM_* constants as keys)
377 * Don't call this function directly: use getFinalParams() to allow
378 * hooks to modify parameters as needed.
380 * Some derived classes may choose to handle an integer $flags parameter
381 * in the overriding methods. Callers of this method can pass zero or
382 * more OR-ed flags like GET_VALUES_FOR_HELP.
386 protected function getAllowedParams( /* $flags = 0 */ ) {
387 // int $flags is not declared because it causes "Strict standards"
388 // warning. Most derived classes do not implement it.
393 * Indicates if this module needs maxlag to be checked
396 public function shouldCheckMaxlag() {
401 * Indicates whether this module requires read rights
404 public function isReadMode() {
409 * Indicates whether this module requires write mode
411 * This should return true for modules that may require synchronous database writes.
412 * Modules that do not need such writes should also not rely on master database access,
413 * since only read queries are needed and each master DB is a single point of failure.
414 * Additionally, requests that only need replica DBs can be efficiently routed to any
415 * datacenter via the Promise-Non-Write-API-Action header.
419 public function isWriteMode() {
424 * Indicates whether this module must be called with a POST request
427 public function mustBePosted() {
428 return $this->needsToken() !== false;
432 * Indicates whether this module is deprecated
436 public function isDeprecated() {
441 * Indicates whether this module is "internal"
442 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
446 public function isInternal() {
451 * Returns the token type this module requires in order to execute.
453 * Modules are strongly encouraged to use the core 'csrf' type unless they
454 * have specialized security needs. If the token type is not one of the
455 * core types, you must use the ApiQueryTokensRegisterTypes hook to
458 * Returning a non-falsey value here will force the addition of an
459 * appropriate 'token' parameter in self::getFinalParams(). Also,
460 * self::mustBePosted() must return true when tokens are used.
462 * In previous versions of MediaWiki, true was a valid return value.
463 * Returning true will generate errors indicating that the API module needs
466 * @return string|false
468 public function needsToken() {
473 * Fetch the salt used in the Web UI corresponding to this module.
475 * Only override this if the Web UI uses a token with a non-constant salt.
478 * @param array $params All supplied parameters for the module
479 * @return string|array|null
481 protected function getWebUITokenSalt( array $params ) {
486 * Returns data for HTTP conditional request mechanisms.
489 * @param string $condition Condition being queried:
490 * - last-modified: Return a timestamp representing the maximum of the
491 * last-modified dates for all resources involved in the request. See
492 * RFC 7232 § 2.2 for semantics.
493 * - etag: Return an entity-tag representing the state of all resources involved
494 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
495 * @return string|bool|null As described above, or null if no value is available.
497 public function getConditionalRequestData( $condition ) {
503 /************************************************************************//**
504 * @name Data access methods
509 * Get the name of the module being executed by this instance
512 public function getModuleName() {
513 return $this->mModuleName
;
517 * Get parameter prefix (usually two letters or an empty string).
520 public function getModulePrefix() {
521 return $this->mModulePrefix
;
525 * Get the main module
528 public function getMain() {
529 return $this->mMainModule
;
533 * Returns true if this module is the main module ($this === $this->mMainModule),
537 public function isMain() {
538 return $this === $this->mMainModule
;
542 * Get the parent of this module
544 * @return ApiBase|null
546 public function getParent() {
547 return $this->isMain() ?
null : $this->getMain();
551 * Returns true if the current request breaks the same-origin policy.
553 * For example, json with callbacks.
555 * https://en.wikipedia.org/wiki/Same-origin_policy
560 public function lacksSameOriginSecurity() {
561 // Main module has this method overridden
562 // Safety - avoid infinite loop:
563 if ( $this->isMain() ) {
564 self
::dieDebug( __METHOD__
, 'base method was called on main module.' );
567 return $this->getMain()->lacksSameOriginSecurity();
571 * Get the path to this module
576 public function getModulePath() {
577 if ( $this->isMain() ) {
579 } elseif ( $this->getParent()->isMain() ) {
580 return $this->getModuleName();
582 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
587 * Get a module from its module path
590 * @param string $path
591 * @return ApiBase|null
592 * @throws ApiUsageException
594 public function getModuleFromPath( $path ) {
595 $module = $this->getMain();
596 if ( $path === 'main' ) {
600 $parts = explode( '+', $path );
601 if ( count( $parts ) === 1 ) {
602 // In case the '+' was typed into URL, it resolves as a space
603 $parts = explode( ' ', $path );
606 $count = count( $parts );
607 for ( $i = 0; $i < $count; $i++
) {
609 $manager = $parent->getModuleManager();
610 if ( $manager === null ) {
611 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
612 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
614 $module = $manager->getModule( $parts[$i] );
616 if ( $module === null ) {
617 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
619 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
629 * Get the result object
632 public function getResult() {
633 // Main module has getResult() method overridden
634 // Safety - avoid infinite loop:
635 if ( $this->isMain() ) {
636 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
639 return $this->getMain()->getResult();
643 * Get the error formatter
644 * @return ApiErrorFormatter
646 public function getErrorFormatter() {
647 // Main module has getErrorFormatter() method overridden
648 // Safety - avoid infinite loop:
649 if ( $this->isMain() ) {
650 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
653 return $this->getMain()->getErrorFormatter();
657 * Gets a default replica DB connection object
660 protected function getDB() {
661 if ( !isset( $this->mSlaveDB
) ) {
662 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
665 return $this->mSlaveDB
;
669 * Get the continuation manager
670 * @return ApiContinuationManager|null
672 public function getContinuationManager() {
673 // Main module has getContinuationManager() method overridden
674 // Safety - avoid infinite loop:
675 if ( $this->isMain() ) {
676 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
679 return $this->getMain()->getContinuationManager();
683 * Set the continuation manager
684 * @param ApiContinuationManager|null $manager
686 public function setContinuationManager( $manager ) {
687 // Main module has setContinuationManager() method overridden
688 // Safety - avoid infinite loop:
689 if ( $this->isMain() ) {
690 self
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
693 $this->getMain()->setContinuationManager( $manager );
698 /************************************************************************//**
699 * @name Parameter handling
704 * Indicate if the module supports dynamically-determined parameters that
705 * cannot be included in self::getAllowedParams().
706 * @return string|array|Message|null Return null if the module does not
707 * support additional dynamic parameters, otherwise return a message
710 public function dynamicParameterDocumentation() {
715 * This method mangles parameter name based on the prefix supplied to the constructor.
716 * Override this method to change parameter name during runtime
717 * @param string|string[] $paramName Parameter name
718 * @return string|string[] Prefixed parameter name
719 * @since 1.29 accepts an array of strings
721 public function encodeParamName( $paramName ) {
722 if ( is_array( $paramName ) ) {
723 return array_map( function ( $name ) {
724 return $this->mModulePrefix
. $name;
727 return $this->mModulePrefix
. $paramName;
732 * Using getAllowedParams(), this function makes an array of the values
733 * provided by the user, with key being the name of the variable, and
734 * value - validated value from user or default. limits will not be
735 * parsed if $parseLimit is set to false; use this when the max
736 * limit is not definitive yet, e.g. when getting revisions.
737 * @param bool $parseLimit True by default
740 public function extractRequestParams( $parseLimit = true ) {
741 // Cache parameters, for performance and to avoid T26564.
742 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
743 $params = $this->getFinalParams();
746 if ( $params ) { // getFinalParams() can return false
747 foreach ( $params as $paramName => $paramSettings ) {
748 $results[$paramName] = $this->getParameterFromSettings(
749 $paramName, $paramSettings, $parseLimit );
752 $this->mParamCache
[$parseLimit] = $results;
755 return $this->mParamCache
[$parseLimit];
759 * Get a value for the given parameter
760 * @param string $paramName Parameter name
761 * @param bool $parseLimit See extractRequestParams()
762 * @return mixed Parameter value
764 protected function getParameter( $paramName, $parseLimit = true ) {
765 $paramSettings = $this->getFinalParams()[$paramName];
767 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
771 * Die if none or more than one of a certain set of parameters is set and not false.
773 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
774 * @param string $required,... Names of parameters of which exactly one must be set
776 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
777 $required = func_get_args();
778 array_shift( $required );
780 $intersection = array_intersect( array_keys( array_filter( $params,
781 [ $this, 'parameterNotEmpty' ] ) ), $required );
783 if ( count( $intersection ) > 1 ) {
784 $this->dieWithError( [
785 'apierror-invalidparammix',
786 Message
::listParam( array_map(
788 return '<var>' . $this->encodeParamName( $p ) . '</var>';
790 array_values( $intersection )
792 count( $intersection ),
794 } elseif ( count( $intersection ) == 0 ) {
795 $this->dieWithError( [
796 'apierror-missingparam-one-of',
797 Message
::listParam( array_map(
799 return '<var>' . $this->encodeParamName( $p ) . '</var>';
801 array_values( $required )
809 * Die if more than one of a certain set of parameters is set and not false.
811 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
812 * @param string $required,... Names of parameters of which at most one must be set
814 public function requireMaxOneParameter( $params, $required /*...*/ ) {
815 $required = func_get_args();
816 array_shift( $required );
818 $intersection = array_intersect( array_keys( array_filter( $params,
819 [ $this, 'parameterNotEmpty' ] ) ), $required );
821 if ( count( $intersection ) > 1 ) {
822 $this->dieWithError( [
823 'apierror-invalidparammix',
824 Message
::listParam( array_map(
826 return '<var>' . $this->encodeParamName( $p ) . '</var>';
828 array_values( $intersection )
830 count( $intersection ),
836 * Die if none of a certain set of parameters is set and not false.
839 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
840 * @param string $required,... Names of parameters of which at least one must be set
842 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
843 $required = func_get_args();
844 array_shift( $required );
846 $intersection = array_intersect(
847 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
851 if ( count( $intersection ) == 0 ) {
852 $this->dieWithError( [
853 'apierror-missingparam-at-least-one-of',
854 Message
::listParam( array_map(
856 return '<var>' . $this->encodeParamName( $p ) . '</var>';
858 array_values( $required )
866 * Die if any of the specified parameters were found in the query part of
867 * the URL rather than the post body.
869 * @param string[] $params Parameters to check
870 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
872 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
873 // Skip if $wgDebugAPI is set or we're in internal mode
874 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
878 $queryValues = $this->getRequest()->getQueryValues();
880 foreach ( $params as $param ) {
881 if ( $prefix !== 'noprefix' ) {
882 $param = $this->encodeParamName( $param );
884 if ( array_key_exists( $param, $queryValues ) ) {
885 $badParams[] = $param;
891 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
897 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
899 * @param object $x Parameter to check is not null/false
902 private function parameterNotEmpty( $x ) {
903 return !is_null( $x ) && $x !== false;
907 * Get a WikiPage object from a title or pageid param, if possible.
908 * Can die, if no param is set or if the title or page id is not valid.
910 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
911 * @param bool|string $load Whether load the object's state from the database:
912 * - false: don't load (if the pageid is given, it will still be loaded)
913 * - 'fromdb': load from a replica DB
914 * - 'fromdbmaster': load from the master database
917 public function getTitleOrPageId( $params, $load = false ) {
918 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
921 if ( isset( $params['title'] ) ) {
922 $titleObj = Title
::newFromText( $params['title'] );
923 if ( !$titleObj ||
$titleObj->isExternal() ) {
924 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
926 if ( !$titleObj->canExist() ) {
927 $this->dieWithError( 'apierror-pagecannotexist' );
929 $pageObj = WikiPage
::factory( $titleObj );
930 if ( $load !== false ) {
931 $pageObj->loadPageData( $load );
933 } elseif ( isset( $params['pageid'] ) ) {
934 if ( $load === false ) {
937 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
939 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
947 * Get a Title object from a title or pageid param, if possible.
948 * Can die, if no param is set or if the title or page id is not valid.
951 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
954 public function getTitleFromTitleOrPageId( $params ) {
955 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
958 if ( isset( $params['title'] ) ) {
959 $titleObj = Title
::newFromText( $params['title'] );
960 if ( !$titleObj ||
$titleObj->isExternal() ) {
961 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
964 } elseif ( isset( $params['pageid'] ) ) {
965 $titleObj = Title
::newFromID( $params['pageid'] );
967 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
975 * Return true if we're to watch the page, false if not, null if no change.
976 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
977 * @param Title $titleObj The page under consideration
978 * @param string $userOption The user option to consider when $watchlist=preferences.
979 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
982 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
983 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
985 switch ( $watchlist ) {
993 # If the user is already watching, don't bother checking
994 if ( $userWatching ) {
997 # If no user option was passed, use watchdefault and watchcreations
998 if ( is_null( $userOption ) ) {
999 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1000 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1003 # Watch the article based on the user preference
1004 return $this->getUser()->getBoolOption( $userOption );
1007 return $userWatching;
1010 return $userWatching;
1015 * Using the settings determine the value for the given parameter
1017 * @param string $paramName Parameter name
1018 * @param array|mixed $paramSettings Default value or an array of settings
1019 * using PARAM_* constants.
1020 * @param bool $parseLimit Parse limit?
1021 * @return mixed Parameter value
1023 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1024 // Some classes may decide to change parameter names
1025 $encParamName = $this->encodeParamName( $paramName );
1028 if ( !is_array( $paramSettings ) ) {
1030 self
::PARAM_DFLT
=> $paramSettings,
1034 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1035 ?
$paramSettings[self
::PARAM_DFLT
]
1037 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1038 ?
$paramSettings[self
::PARAM_ISMULTI
]
1040 $multiLimit1 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT1
] )
1041 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT1
]
1043 $multiLimit2 = isset( $paramSettings[self
::PARAM_ISMULTI_LIMIT2
] )
1044 ?
$paramSettings[self
::PARAM_ISMULTI_LIMIT2
]
1046 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1047 ?
$paramSettings[self
::PARAM_TYPE
]
1049 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1050 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1052 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1053 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1055 $deprecatedValues = isset( $paramSettings[self
::PARAM_DEPRECATED_VALUES
] )
1056 ?
$paramSettings[self
::PARAM_DEPRECATED_VALUES
]
1058 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1059 ?
$paramSettings[self
::PARAM_REQUIRED
]
1061 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1062 ?
$paramSettings[self
::PARAM_ALL
]
1065 // When type is not given, and no choices, the type is the same as $default
1066 if ( !isset( $type ) ) {
1067 if ( isset( $default ) ) {
1068 $type = gettype( $default );
1070 $type = 'NULL'; // allow everything
1074 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1075 $this->getMain()->markParamsSensitive( $encParamName );
1078 if ( $type == 'boolean' ) {
1079 if ( isset( $default ) && $default !== false ) {
1080 // Having a default value of anything other than 'false' is not allowed
1083 "Boolean param $encParamName's default is set to '$default'. " .
1084 'Boolean parameters must default to false.'
1088 $value = $this->getMain()->getCheck( $encParamName );
1089 } elseif ( $type == 'upload' ) {
1090 if ( isset( $default ) ) {
1091 // Having a default value is not allowed
1094 "File upload param $encParamName's default is set to " .
1095 "'$default'. File upload parameters may not have a default." );
1098 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1100 $value = $this->getMain()->getUpload( $encParamName );
1101 if ( !$value->exists() ) {
1102 // This will get the value without trying to normalize it
1103 // (because trying to normalize a large binary file
1104 // accidentally uploaded as a field fails spectacularly)
1105 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1106 if ( $value !== null ) {
1107 $this->dieWithError(
1108 [ 'apierror-badupload', $encParamName ],
1109 "badupload_{$encParamName}"
1114 $value = $this->getMain()->getVal( $encParamName, $default );
1116 if ( isset( $value ) && $type == 'namespace' ) {
1117 $type = MWNamespace
::getValidNamespaces();
1118 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1119 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1121 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1123 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1127 if ( isset( $value ) && $type == 'submodule' ) {
1128 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1129 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1131 $type = $this->getModuleManager()->getNames( $paramName );
1135 $request = $this->getMain()->getRequest();
1136 $rawValue = $request->getRawVal( $encParamName );
1137 if ( $rawValue === null ) {
1138 $rawValue = $default;
1141 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1142 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1144 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1145 // done by WebRequest for $_GET. Let's call that a feature.
1146 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1148 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1152 // Check for NFC normalization, and warn
1153 if ( $rawValue !== $value ) {
1154 $this->handleParamNormalization( $paramName, $value, $rawValue );
1158 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1159 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1162 "For param $encParamName, PARAM_ALL collides with a possible value" );
1164 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1165 $value = $this->parseMultiValue(
1169 is_array( $type ) ?
$type : null,
1170 $allowAll ?
$allSpecifier : null,
1176 // More validation only when choices were not given
1177 // choices were validated in parseMultiValue()
1178 if ( isset( $value ) ) {
1179 if ( !is_array( $type ) ) {
1181 case 'NULL': // nothing to do
1186 if ( $required && $value === '' ) {
1187 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1190 case 'integer': // Force everything using intval() and optionally validate limits
1191 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1192 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1193 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1194 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1196 if ( is_array( $value ) ) {
1197 $value = array_map( 'intval', $value );
1198 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1199 foreach ( $value as &$v ) {
1200 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1204 $value = intval( $value );
1205 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1206 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1211 if ( !$parseLimit ) {
1212 // Don't do any validation whatsoever
1215 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1216 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1220 "MAX1 or MAX2 are not defined for the limit $encParamName"
1224 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1226 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1227 if ( $value == 'max' ) {
1228 $value = $this->getMain()->canApiHighLimits()
1229 ?
$paramSettings[self
::PARAM_MAX2
]
1230 : $paramSettings[self
::PARAM_MAX
];
1231 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1233 $value = intval( $value );
1234 $this->validateLimit(
1238 $paramSettings[self
::PARAM_MAX
],
1239 $paramSettings[self
::PARAM_MAX2
]
1245 self
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1249 if ( is_array( $value ) ) {
1250 foreach ( $value as $key => $val ) {
1251 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1254 $value = $this->validateTimestamp( $value, $encParamName );
1258 if ( is_array( $value ) ) {
1259 foreach ( $value as $key => $val ) {
1260 $value[$key] = $this->validateUser( $val, $encParamName );
1263 $value = $this->validateUser( $value, $encParamName );
1266 case 'upload': // nothing to do
1269 // If change tagging was requested, check that the tags are valid.
1270 if ( !is_array( $value ) && !$multi ) {
1271 $value = [ $value ];
1273 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1274 if ( !$tagsStatus->isGood() ) {
1275 $this->dieStatus( $tagsStatus );
1279 self
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1283 // Throw out duplicates if requested
1284 if ( !$dupes && is_array( $value ) ) {
1285 $value = array_unique( $value );
1288 // Set a warning if a deprecated parameter has been passed
1289 if ( $deprecated && $value !== false ) {
1290 $feature = $encParamName;
1292 while ( !$m->isMain() ) {
1293 $p = $m->getParent();
1294 $name = $m->getModuleName();
1295 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1296 $feature = "{$param}={$name}&{$feature}";
1299 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1302 // Set a warning if a deprecated parameter value has been passed
1303 $usedDeprecatedValues = $deprecatedValues && $value !== false
1304 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1306 if ( $usedDeprecatedValues ) {
1307 $feature = "$encParamName=";
1309 while ( !$m->isMain() ) {
1310 $p = $m->getParent();
1311 $name = $m->getModuleName();
1312 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1313 $feature = "{$param}={$name}&{$feature}";
1316 foreach ( $usedDeprecatedValues as $v ) {
1317 $msg = $deprecatedValues[$v];
1318 if ( $msg === true ) {
1319 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1321 $this->addDeprecation( $msg, "$feature$v" );
1324 } elseif ( $required ) {
1325 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1332 * Handle when a parameter was Unicode-normalized
1334 * @param string $paramName Unprefixed parameter name
1335 * @param string $value Input that will be used.
1336 * @param string $rawValue Input before normalization.
1338 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1339 $encParamName = $this->encodeParamName( $paramName );
1340 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1344 * Split a multi-valued parameter string, like explode()
1346 * @param string $value
1350 protected function explodeMultiValue( $value, $limit ) {
1351 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1353 $value = substr( $value, 1 );
1358 return explode( $sep, $value, $limit );
1362 * Return an array of values that were given in a 'a|b|c' notation,
1363 * after it optionally validates them against the list allowed values.
1365 * @param string $valueName The name of the parameter (for error
1367 * @param mixed $value The value being parsed
1368 * @param bool $allowMultiple Can $value contain more than one value
1370 * @param string[]|null $allowedValues An array of values to check against. If
1371 * null, all values are accepted.
1372 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1373 * if this behavior should not be allowed
1374 * @param int|null $limit1 Maximum number of values, for normal users.
1375 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1376 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1378 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1379 $allSpecifier = null, $limit1 = null, $limit2 = null
1381 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1384 $limit1 = $limit1 ?
: self
::LIMIT_SML1
;
1385 $limit2 = $limit2 ?
: self
::LIMIT_SML2
;
1387 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1388 // because it unstubs $wgUser
1389 $valuesList = $this->explodeMultiValue( $value, $limit2 +
1 );
1390 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule
->canApiHighLimits()
1394 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1395 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1397 return $allowedValues;
1400 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1401 $this->addDeprecation(
1402 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1403 "too-many-$valueName-for-{$this->getModulePath()}"
1407 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1408 // T35482 - Allow entries with | in them for non-multiple values
1409 if ( in_array( $value, $allowedValues, true ) ) {
1413 if ( is_array( $allowedValues ) ) {
1414 $values = array_map( function ( $v ) {
1415 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1416 }, $allowedValues );
1417 $this->dieWithError( [
1418 'apierror-multival-only-one-of',
1420 Message
::listParam( $values ),
1422 ], "multival_$valueName" );
1424 $this->dieWithError( [
1425 'apierror-multival-only-one',
1427 ], "multival_$valueName" );
1431 if ( is_array( $allowedValues ) ) {
1432 // Check for unknown values
1433 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1434 if ( count( $unknown ) ) {
1435 if ( $allowMultiple ) {
1436 $this->addWarning( [
1437 'apiwarn-unrecognizedvalues',
1439 Message
::listParam( $unknown, 'comma' ),
1443 $this->dieWithError(
1444 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1445 "unknown_$valueName"
1449 // Now throw them out
1450 $valuesList = array_intersect( $valuesList, $allowedValues );
1453 return $allowMultiple ?
$valuesList : $valuesList[0];
1457 * Validate the value against the minimum and user/bot maximum limits.
1458 * Prints usage info on failure.
1459 * @param string $paramName Parameter name
1460 * @param int &$value Parameter value
1461 * @param int|null $min Minimum value
1462 * @param int|null $max Maximum value for users
1463 * @param int $botMax Maximum value for sysops/bots
1464 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1466 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1467 $enforceLimits = false
1469 if ( !is_null( $min ) && $value < $min ) {
1470 $msg = ApiMessage
::create(
1471 [ 'apierror-integeroutofrange-belowminimum',
1472 $this->encodeParamName( $paramName ), $min, $value ],
1473 'integeroutofrange',
1474 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1476 $this->warnOrDie( $msg, $enforceLimits );
1480 // Minimum is always validated, whereas maximum is checked only if not
1481 // running in internal call mode
1482 if ( $this->getMain()->isInternalMode() ) {
1486 // Optimization: do not check user's bot status unless really needed -- skips db query
1487 // assumes $botMax >= $max
1488 if ( !is_null( $max ) && $value > $max ) {
1489 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1490 if ( $value > $botMax ) {
1491 $msg = ApiMessage
::create(
1492 [ 'apierror-integeroutofrange-abovebotmax',
1493 $this->encodeParamName( $paramName ), $botMax, $value ],
1494 'integeroutofrange',
1495 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1497 $this->warnOrDie( $msg, $enforceLimits );
1501 $msg = ApiMessage
::create(
1502 [ 'apierror-integeroutofrange-abovemax',
1503 $this->encodeParamName( $paramName ), $max, $value ],
1504 'integeroutofrange',
1505 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1507 $this->warnOrDie( $msg, $enforceLimits );
1514 * Validate and normalize of parameters of type 'timestamp'
1515 * @param string $value Parameter value
1516 * @param string $encParamName Parameter name
1517 * @return string Validated and normalized parameter
1519 protected function validateTimestamp( $value, $encParamName ) {
1520 // Confusing synonyms for the current time accepted by wfTimestamp()
1521 // (wfTimestamp() also accepts various non-strings and the string of 14
1522 // ASCII NUL bytes, but those can't get here)
1524 $this->addDeprecation(
1525 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1526 'unclear-"now"-timestamp'
1528 return wfTimestamp( TS_MW
);
1531 // Explicit synonym for the current time
1532 if ( $value === 'now' ) {
1533 return wfTimestamp( TS_MW
);
1536 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1537 if ( $unixTimestamp === false ) {
1538 $this->dieWithError(
1539 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1540 "badtimestamp_{$encParamName}"
1544 return wfTimestamp( TS_MW
, $unixTimestamp );
1548 * Validate the supplied token.
1551 * @param string $token Supplied token
1552 * @param array $params All supplied parameters for the module
1554 * @throws MWException
1556 final public function validateToken( $token, array $params ) {
1557 $tokenType = $this->needsToken();
1558 $salts = ApiQueryTokens
::getTokenTypeSalts();
1559 if ( !isset( $salts[$tokenType] ) ) {
1560 throw new MWException(
1561 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1562 'without registering it'
1566 $tokenObj = ApiQueryTokens
::getToken(
1567 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1569 if ( $tokenObj->match( $token ) ) {
1573 $webUiSalt = $this->getWebUITokenSalt( $params );
1574 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1586 * Validate and normalize of parameters of type 'user'
1587 * @param string $value Parameter value
1588 * @param string $encParamName Parameter name
1589 * @return string Validated and normalized parameter
1591 private function validateUser( $value, $encParamName ) {
1592 $title = Title
::makeTitleSafe( NS_USER
, $value );
1593 if ( $title === null ||
$title->hasFragment() ) {
1594 $this->dieWithError(
1595 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1596 "baduser_{$encParamName}"
1600 return $title->getText();
1605 /************************************************************************//**
1606 * @name Utility methods
1611 * Set a watch (or unwatch) based the based on a watchlist parameter.
1612 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1613 * @param Title $titleObj The article's title to change
1614 * @param string $userOption The user option to consider when $watch=preferences
1616 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1617 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1618 if ( $value === null ) {
1622 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1626 * Truncate an array to a certain length.
1627 * @param array &$arr Array to truncate
1628 * @param int $limit Maximum length
1629 * @return bool True if the array was truncated, false otherwise
1631 public static function truncateArray( &$arr, $limit ) {
1633 while ( count( $arr ) > $limit ) {
1642 * Gets the user for whom to get the watchlist
1644 * @param array $params
1647 public function getWatchlistUser( $params ) {
1648 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1649 $user = User
::newFromName( $params['owner'], false );
1650 if ( !( $user && $user->getId() ) ) {
1651 $this->dieWithError(
1652 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1655 $token = $user->getOption( 'watchlisttoken' );
1656 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1657 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1660 if ( !$this->getUser()->isLoggedIn() ) {
1661 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1663 $this->checkUserRightsAny( 'viewmywatchlist' );
1664 $user = $this->getUser();
1671 * A subset of wfEscapeWikiText for BC texts
1674 * @param string|array $v
1675 * @return string|array
1677 private static function escapeWikiText( $v ) {
1678 if ( is_array( $v ) ) {
1679 return array_map( 'self::escapeWikiText', $v );
1682 '__' => '__', '{' => '{', '}' => '}',
1683 '[[Category:' => '[[:Category:',
1684 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1690 * Create a Message from a string or array
1692 * A string is used as a message key. An array has the message key as the
1693 * first value and message parameters as subsequent values.
1696 * @param string|array|Message $msg
1697 * @param IContextSource $context
1698 * @param array $params
1699 * @return Message|null
1701 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1702 if ( is_string( $msg ) ) {
1703 $msg = wfMessage( $msg );
1704 } elseif ( is_array( $msg ) ) {
1705 $msg = call_user_func_array( 'wfMessage', $msg );
1707 if ( !$msg instanceof Message
) {
1711 $msg->setContext( $context );
1713 $msg->params( $params );
1720 * Turn an array of message keys or key+param arrays into a Status
1722 * @param array $errors
1723 * @param User|null $user
1726 public function errorArrayToStatus( array $errors, User
$user = null ) {
1727 if ( $user === null ) {
1728 $user = $this->getUser();
1731 $status = Status
::newGood();
1732 foreach ( $errors as $error ) {
1733 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1734 $status->fatal( ApiMessage
::create(
1737 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1739 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1740 $status->fatal( ApiMessage
::create(
1741 'apierror-autoblocked',
1743 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1745 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1746 $status->fatal( ApiMessage
::create(
1747 'apierror-systemblocked',
1749 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1752 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1760 /************************************************************************//**
1761 * @name Warning and error reporting
1766 * Add a warning for this module.
1768 * Users should monitor this section to notice any changes in API. Multiple
1769 * calls to this function will result in multiple warning messages.
1771 * If $msg is not an ApiMessage, the message code will be derived from the
1772 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1775 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1776 * @param string|null $code See ApiErrorFormatter::addWarning()
1777 * @param array|null $data See ApiErrorFormatter::addWarning()
1779 public function addWarning( $msg, $code = null, $data = null ) {
1780 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1784 * Add a deprecation warning for this module.
1786 * A combination of $this->addWarning() and $this->logFeatureUsage()
1789 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1790 * @param string|null $feature See ApiBase::logFeatureUsage()
1791 * @param array|null $data See ApiErrorFormatter::addWarning()
1793 public function addDeprecation( $msg, $feature, $data = [] ) {
1794 $data = (array)$data;
1795 if ( $feature !== null ) {
1796 $data['feature'] = $feature;
1797 $this->logFeatureUsage( $feature );
1799 $this->addWarning( $msg, 'deprecation', $data );
1801 // No real need to deduplicate here, ApiErrorFormatter does that for
1802 // us (assuming the hook is deterministic).
1803 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1804 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1805 if ( count( $msgs ) > 1 ) {
1806 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1807 $msg = ( new RawMessage( $key ) )->params( $msgs );
1809 $msg = reset( $msgs );
1811 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1815 * Add an error for this module without aborting
1817 * If $msg is not an ApiMessage, the message code will be derived from the
1818 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1820 * @note If you want to abort processing, use self::dieWithError() instead.
1822 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1823 * @param string|null $code See ApiErrorFormatter::addError()
1824 * @param array|null $data See ApiErrorFormatter::addError()
1826 public function addError( $msg, $code = null, $data = null ) {
1827 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1831 * Add warnings and/or errors from a Status
1833 * @note If you want to abort processing, use self::dieStatus() instead.
1835 * @param StatusValue $status
1836 * @param string[] $types 'warning' and/or 'error'
1838 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1839 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1843 * Abort execution with an error
1845 * If $msg is not an ApiMessage, the message code will be derived from the
1846 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1849 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1850 * @param string|null $code See ApiErrorFormatter::addError()
1851 * @param array|null $data See ApiErrorFormatter::addError()
1852 * @param int|null $httpCode HTTP error code to use
1853 * @throws ApiUsageException always
1855 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1856 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1860 * Abort execution with an error derived from an exception
1863 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1864 * @param array $options See ApiErrorFormatter::getMessageFromException()
1865 * @throws ApiUsageException always
1867 public function dieWithException( $exception, array $options = [] ) {
1868 $this->dieWithError(
1869 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1874 * Adds a warning to the output, else dies
1876 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1877 * @param bool $enforceLimits Whether this is an enforce (die)
1879 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1880 if ( $enforceLimits ) {
1881 $this->dieWithError( $msg );
1883 $this->addWarning( $msg );
1888 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1889 * error handler and die with an error message including block info.
1892 * @param Block $block The block used to generate the ApiUsageException
1893 * @throws ApiUsageException always
1895 public function dieBlocked( Block
$block ) {
1896 // Die using the appropriate message depending on block type
1897 if ( $block->getType() == Block
::TYPE_AUTO
) {
1898 $this->dieWithError(
1899 'apierror-autoblocked',
1901 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1904 $this->dieWithError(
1907 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1913 * Throw an ApiUsageException based on the Status object.
1916 * @since 1.29 Accepts a StatusValue
1917 * @param StatusValue $status
1918 * @throws ApiUsageException always
1920 public function dieStatus( StatusValue
$status ) {
1921 if ( $status->isGood() ) {
1922 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1925 // ApiUsageException needs a fatal status, but this method has
1926 // historically accepted any non-good status. Convert it if necessary.
1927 $status->setOK( false );
1928 if ( !$status->getErrorsByType( 'error' ) ) {
1929 $newStatus = Status
::newGood();
1930 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1931 call_user_func_array(
1932 [ $newStatus, 'fatal' ],
1933 array_merge( [ $err['message'] ], $err['params'] )
1936 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1937 $newStatus->fatal( 'unknownerror-nocode' );
1939 $status = $newStatus;
1942 throw new ApiUsageException( $this, $status );
1946 * Helper function for readonly errors
1948 * @throws ApiUsageException always
1950 public function dieReadOnly() {
1951 $this->dieWithError(
1952 'apierror-readonly',
1954 [ 'readonlyreason' => wfReadOnlyReason() ]
1959 * Helper function for permission-denied errors
1961 * @param string|string[] $rights
1962 * @param User|null $user
1963 * @throws ApiUsageException if the user doesn't have any of the rights.
1964 * The error message is based on $rights[0].
1966 public function checkUserRightsAny( $rights, $user = null ) {
1968 $user = $this->getUser();
1970 $rights = (array)$rights;
1971 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1972 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1977 * Helper function for permission-denied errors
1979 * @param Title $title
1980 * @param string|string[] $actions
1981 * @param User|null $user
1982 * @throws ApiUsageException if the user doesn't have all of the rights.
1984 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1986 $user = $this->getUser();
1990 foreach ( (array)$actions as $action ) {
1991 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1994 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1999 * Will only set a warning instead of failing if the global $wgDebugAPI
2000 * is set to true. Otherwise behaves exactly as self::dieWithError().
2003 * @param string|array|Message $msg
2004 * @param string|null $code
2005 * @param array|null $data
2006 * @param int|null $httpCode
2007 * @throws ApiUsageException
2009 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2010 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2011 $this->dieWithError( $msg, $code, $data, $httpCode );
2013 $this->addWarning( $msg, $code, $data );
2018 * Die with the 'badcontinue' error.
2020 * This call is common enough to make it into the base method.
2022 * @param bool $condition Will only die if this value is true
2023 * @throws ApiUsageException
2026 protected function dieContinueUsageIf( $condition ) {
2028 $this->dieWithError( 'apierror-badcontinue' );
2033 * Internal code errors should be reported with this method
2034 * @param string $method Method or function name
2035 * @param string $message Error message
2036 * @throws MWException always
2038 protected static function dieDebug( $method, $message ) {
2039 throw new MWException( "Internal error in $method: $message" );
2043 * Write logging information for API features to a debug log, for usage
2045 * @note Consider using $this->addDeprecation() instead to both warn and log.
2046 * @param string $feature Feature being used.
2048 public function logFeatureUsage( $feature ) {
2049 $request = $this->getRequest();
2050 $s = '"' . addslashes( $feature ) . '"' .
2051 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2052 ' "' . $request->getIP() . '"' .
2053 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2054 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2055 wfDebugLog( 'api-feature-usage', $s, 'private' );
2060 /************************************************************************//**
2061 * @name Help message generation
2066 * Return the summary message.
2068 * This is a one-line description of the module, suitable for display in a
2072 * @return string|array|Message
2074 protected function getSummaryMessage() {
2075 return "apihelp-{$this->getModulePath()}-summary";
2079 * Return the extended help text message.
2081 * This is additional text to display at the top of the help section, below
2085 * @return string|array|Message
2087 protected function getExtendedDescription() {
2089 "apihelp-{$this->getModulePath()}-extended-description",
2090 'api-help-no-extended-description',
2095 * Get final module summary
2097 * Ideally this will just be the getSummaryMessage(). However, for
2098 * backwards compatibility, if that message does not exist then the first
2099 * line of wikitext from the description message will be used instead.
2104 public function getFinalSummary() {
2105 $msg = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2106 $this->getModulePrefix(),
2107 $this->getModuleName(),
2108 $this->getModulePath(),
2110 if ( !$msg->exists() ) {
2111 wfDeprecated( 'API help "description" messages', '1.30' );
2112 $msg = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2113 $this->getModulePrefix(),
2114 $this->getModuleName(),
2115 $this->getModulePath(),
2117 $msg = self
::makeMessage( 'rawmessage', $this->getContext(), [
2118 preg_replace( '/\n.*/s', '', $msg->text() )
2125 * Get final module description, after hooks have had a chance to tweak it as
2128 * @since 1.25, returns Message[] rather than string[]
2131 public function getFinalDescription() {
2132 $desc = $this->getDescription();
2134 // Avoid PHP 7.1 warning of passing $this by reference
2136 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2137 $desc = self
::escapeWikiText( $desc );
2138 if ( is_array( $desc ) ) {
2139 $desc = implode( "\n", $desc );
2141 $desc = (string)$desc;
2144 $summary = self
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2145 $this->getModulePrefix(),
2146 $this->getModuleName(),
2147 $this->getModulePath(),
2149 $extendedDescription = self
::makeMessage(
2150 $this->getExtendedDescription(), $this->getContext(), [
2151 $this->getModulePrefix(),
2152 $this->getModuleName(),
2153 $this->getModulePath(),
2157 if ( $summary->exists() ) {
2158 $msgs = [ $summary, $extendedDescription ];
2160 wfDeprecated( 'API help "description" messages', '1.30' );
2161 $description = self
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2162 $this->getModulePrefix(),
2163 $this->getModuleName(),
2164 $this->getModulePath(),
2166 if ( !$description->exists() ) {
2167 $description = $this->msg( 'api-help-fallback-description', $desc );
2169 $msgs = [ $description ];
2172 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2178 * Get final list of parameters, after hooks have had a chance to
2179 * tweak it as needed.
2181 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2182 * @return array|bool False on no parameters
2183 * @since 1.21 $flags param added
2185 public function getFinalParams( $flags = 0 ) {
2186 $params = $this->getAllowedParams( $flags );
2191 if ( $this->needsToken() ) {
2192 $params['token'] = [
2193 self
::PARAM_TYPE
=> 'string',
2194 self
::PARAM_REQUIRED
=> true,
2195 self
::PARAM_SENSITIVE
=> true,
2196 self
::PARAM_HELP_MSG
=> [
2197 'api-help-param-token',
2198 $this->needsToken(),
2200 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2203 // Avoid PHP 7.1 warning of passing $this by reference
2205 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2211 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2214 * @since 1.25, returns array of Message[] rather than array of string[]
2215 * @return array Keys are parameter names, values are arrays of Message objects
2217 public function getFinalParamDescription() {
2218 $prefix = $this->getModulePrefix();
2219 $name = $this->getModuleName();
2220 $path = $this->getModulePath();
2222 $desc = $this->getParamDescription();
2224 // Avoid PHP 7.1 warning of passing $this by reference
2226 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2231 $desc = self
::escapeWikiText( $desc );
2233 $params = $this->getFinalParams( self
::GET_VALUES_FOR_HELP
);
2235 foreach ( $params as $param => $settings ) {
2236 if ( !is_array( $settings ) ) {
2240 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2241 if ( is_array( $d ) ) {
2242 // Special handling for prop parameters
2243 $d = array_map( function ( $line ) {
2244 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2245 $line = "\n;{$m[1]}:{$m[2]}";
2249 $d = implode( ' ', $d );
2252 if ( isset( $settings[self
::PARAM_HELP_MSG
] ) ) {
2253 $msg = $settings[self
::PARAM_HELP_MSG
];
2255 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2256 if ( !$msg->exists() ) {
2257 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2260 $msg = self
::makeMessage( $msg, $this->getContext(),
2261 [ $prefix, $param, $name, $path ] );
2263 self
::dieDebug( __METHOD__
,
2264 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2266 $msgs[$param] = [ $msg ];
2268 if ( isset( $settings[self
::PARAM_TYPE
] ) &&
2269 $settings[self
::PARAM_TYPE
] === 'submodule'
2271 if ( isset( $settings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2272 $map = $settings[self
::PARAM_SUBMODULE_MAP
];
2274 $prefix = $this->isMain() ?
'' : ( $this->getModulePath() . '+' );
2276 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2277 $map[$submoduleName] = $prefix . $submoduleName;
2282 $deprecatedSubmodules = [];
2283 foreach ( $map as $v => $m ) {
2284 $arr = &$submodules;
2285 $isDeprecated = false;
2288 $submod = $this->getModuleFromPath( $m );
2290 $summary = $submod->getFinalSummary();
2291 $isDeprecated = $submod->isDeprecated();
2292 if ( $isDeprecated ) {
2293 $arr = &$deprecatedSubmodules;
2296 } catch ( ApiUsageException
$ex ) {
2300 $key = $summary->getKey();
2301 $params = $summary->getParams();
2303 $key = 'api-help-undocumented-module';
2306 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2307 $arr[] = $m->setContext( $this->getContext() );
2309 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2310 } elseif ( isset( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2311 if ( !is_array( $settings[self
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2312 self
::dieDebug( __METHOD__
,
2313 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2315 if ( !is_array( $settings[self
::PARAM_TYPE
] ) ) {
2316 self
::dieDebug( __METHOD__
,
2317 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2318 'ApiBase::PARAM_TYPE is an array' );
2321 $valueMsgs = $settings[self
::PARAM_HELP_MSG_PER_VALUE
];
2322 $deprecatedValues = isset( $settings[self
::PARAM_DEPRECATED_VALUES
] )
2323 ?
$settings[self
::PARAM_DEPRECATED_VALUES
]
2326 foreach ( $settings[self
::PARAM_TYPE
] as $value ) {
2327 if ( isset( $valueMsgs[$value] ) ) {
2328 $msg = $valueMsgs[$value];
2330 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2332 $m = self
::makeMessage( $msg, $this->getContext(),
2333 [ $prefix, $param, $name, $path, $value ] );
2335 $m = new ApiHelpParamValueMessage(
2337 [ $m->getKey(), 'api-help-param-no-description' ],
2339 isset( $deprecatedValues[$value] )
2341 $msgs[$param][] = $m->setContext( $this->getContext() );
2343 self
::dieDebug( __METHOD__
,
2344 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2349 if ( isset( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2350 if ( !is_array( $settings[self
::PARAM_HELP_MSG_APPEND
] ) ) {
2351 self
::dieDebug( __METHOD__
,
2352 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2354 foreach ( $settings[self
::PARAM_HELP_MSG_APPEND
] as $m ) {
2355 $m = self
::makeMessage( $m, $this->getContext(),
2356 [ $prefix, $param, $name, $path ] );
2358 $msgs[$param][] = $m;
2360 self
::dieDebug( __METHOD__
,
2361 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2367 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2373 * Generates the list of flags for the help screen and for action=paraminfo
2375 * Corresponding messages: api-help-flag-deprecated,
2376 * api-help-flag-internal, api-help-flag-readrights,
2377 * api-help-flag-writerights, api-help-flag-mustbeposted
2381 protected function getHelpFlags() {
2384 if ( $this->isDeprecated() ) {
2385 $flags[] = 'deprecated';
2387 if ( $this->isInternal() ) {
2388 $flags[] = 'internal';
2390 if ( $this->isReadMode() ) {
2391 $flags[] = 'readrights';
2393 if ( $this->isWriteMode() ) {
2394 $flags[] = 'writerights';
2396 if ( $this->mustBePosted() ) {
2397 $flags[] = 'mustbeposted';
2404 * Returns information about the source of this module, if known
2406 * Returned array is an array with the following keys:
2407 * - path: Install path
2408 * - name: Extension name, or "MediaWiki" for core
2409 * - namemsg: (optional) i18n message key for a display name
2410 * - license-name: (optional) Name of license
2412 * @return array|null
2414 protected function getModuleSourceInfo() {
2417 if ( $this->mModuleSource
!== false ) {
2418 return $this->mModuleSource
;
2421 // First, try to find where the module comes from...
2422 $rClass = new ReflectionClass( $this );
2423 $path = $rClass->getFileName();
2426 $this->mModuleSource
= null;
2429 $path = realpath( $path ) ?
: $path;
2431 // Build map of extension directories to extension info
2432 if ( self
::$extensionInfo === null ) {
2433 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2434 self
::$extensionInfo = [
2435 realpath( __DIR__
) ?
: __DIR__
=> [
2437 'name' => 'MediaWiki',
2438 'license-name' => 'GPL-2.0+',
2440 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2441 realpath( $extDir ) ?
: $extDir => null,
2447 'license-name' => null,
2449 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2450 foreach ( $group as $ext ) {
2451 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2452 // This shouldn't happen, but does anyway.
2456 $extpath = $ext['path'];
2457 if ( !is_dir( $extpath ) ) {
2458 $extpath = dirname( $extpath );
2460 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2461 array_intersect_key( $ext, $keep );
2464 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2465 $extpath = $ext['path'];
2466 if ( !is_dir( $extpath ) ) {
2467 $extpath = dirname( $extpath );
2469 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2470 array_intersect_key( $ext, $keep );
2474 // Now traverse parent directories until we find a match or run out of
2477 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2479 $this->mModuleSource
= self
::$extensionInfo[$path];
2480 return $this->mModuleSource
;
2484 $path = dirname( $path );
2485 } while ( $path !== $oldpath );
2487 // No idea what extension this might be.
2488 $this->mModuleSource
= null;
2493 * Called from ApiHelp before the pieces are joined together and returned.
2495 * This exists mainly for ApiMain to add the Permissions and Credits
2496 * sections. Other modules probably don't need it.
2498 * @param string[] &$help Array of help data
2499 * @param array $options Options passed to ApiHelp::getHelp
2500 * @param array &$tocData If a TOC is being generated, this array has keys
2501 * as anchors in the page and values as for Linker::generateTOC().
2503 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2508 /************************************************************************//**
2514 * Returns the description string for this module
2516 * Ignored if an i18n message exists for
2517 * "apihelp-{$this->getModulePath()}-description".
2519 * @deprecated since 1.25
2520 * @return Message|string|array|false
2522 protected function getDescription() {
2527 * Returns an array of parameter descriptions.
2529 * For each parameter, ignored if an i18n message exists for the parameter.
2530 * By default that message is
2531 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2532 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2533 * self::getFinalParams().
2535 * @deprecated since 1.25
2536 * @return array|bool False on no parameter descriptions
2538 protected function getParamDescription() {
2543 * Returns usage examples for this module.
2545 * Return value as an array is either:
2546 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2548 * - sequential numeric keys with even-numbered keys being display-text
2549 * and odd-numbered keys being partial urls
2550 * - partial URLs as keys with display-text (string or array-to-be-joined)
2552 * Return value as a string is the same as an array with a numeric key and
2553 * that value, and boolean false means "no examples".
2555 * @deprecated since 1.25, use getExamplesMessages() instead
2556 * @return bool|string|array
2558 protected function getExamples() {
2563 * @deprecated since 1.25, always returns empty string
2564 * @param IDatabase|bool $db
2567 public function getModuleProfileName( $db = false ) {
2568 wfDeprecated( __METHOD__
, '1.25' );
2573 * @deprecated since 1.25
2575 public function profileIn() {
2576 // No wfDeprecated() yet because extensions call this and might need to
2577 // keep doing so for BC.
2581 * @deprecated since 1.25
2583 public function profileOut() {
2584 // No wfDeprecated() yet because extensions call this and might need to
2585 // keep doing so for BC.
2589 * @deprecated since 1.25
2591 public function safeProfileOut() {
2592 wfDeprecated( __METHOD__
, '1.25' );
2596 * @deprecated since 1.25, always returns 0
2599 public function getProfileTime() {
2600 wfDeprecated( __METHOD__
, '1.25' );
2605 * @deprecated since 1.25
2607 public function profileDBIn() {
2608 wfDeprecated( __METHOD__
, '1.25' );
2612 * @deprecated since 1.25
2614 public function profileDBOut() {
2615 wfDeprecated( __METHOD__
, '1.25' );
2619 * @deprecated since 1.25, always returns 0
2622 public function getProfileDBTime() {
2623 wfDeprecated( __METHOD__
, '1.25' );
2628 * Call wfTransactionalTimeLimit() if this request was POSTed
2631 protected function useTransactionalTimeLimit() {
2632 if ( $this->getRequest()->wasPosted() ) {
2633 wfTransactionalTimeLimit();
2638 * @deprecated since 1.29, use ApiBase::addWarning() instead
2639 * @param string $warning Warning message
2641 public function setWarning( $warning ) {
2642 wfDeprecated( __METHOD__
, '1.29' );
2643 $msg = new ApiRawMessage( $warning, 'warning' );
2644 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2648 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2649 * error handler and die with an error message.
2651 * @deprecated since 1.29, use self::dieWithError() instead
2652 * @param string $description One-line human-readable description of the
2653 * error condition, e.g., "The API requires a valid action parameter"
2654 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2655 * automated identification of the error, e.g., 'unknown_action'
2656 * @param int $httpRespCode HTTP response code
2657 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2658 * @throws ApiUsageException always
2660 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2661 wfDeprecated( __METHOD__
, '1.29' );
2662 $this->dieWithError(
2663 new RawMessage( '$1', [ $description ] ),
2671 * Get error (as code, string) from a Status object.
2674 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2675 * @param Status $status
2676 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2677 * @return array Array of code and error string
2678 * @throws MWException
2680 public function getErrorFromStatus( $status, &$extraData = null ) {
2681 wfDeprecated( __METHOD__
, '1.29' );
2682 if ( $status->isGood() ) {
2683 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2686 $errors = $status->getErrorsByType( 'error' );
2688 // No errors? Assume the warnings should be treated as errors
2689 $errors = $status->getErrorsByType( 'warning' );
2692 // Still no errors? Punt
2693 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2696 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2697 $msg = $errors[0]['message'];
2699 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2701 if ( !$msg instanceof IApiMessage
) {
2702 $key = $msg->getKey();
2703 $params = $msg->getParams();
2704 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2705 $msg = ApiMessage
::create( $params );
2710 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2715 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2716 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2717 * API codes and message texts, and a few interfaces required poking
2718 * something in here. Now we're repurposing it to map those same strings
2719 * to i18n messages, and declaring that any interface that requires poking
2720 * at this is broken and needs replacing ASAP.
2722 private static $messageMap = [
2723 'unknownerror' => 'apierror-unknownerror',
2724 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2725 'ns-specialprotected' => 'ns-specialprotected',
2726 'protectedinterface' => 'protectedinterface',
2727 'namespaceprotected' => 'namespaceprotected',
2728 'customcssprotected' => 'customcssprotected',
2729 'customjsprotected' => 'customjsprotected',
2730 'cascadeprotected' => 'cascadeprotected',
2731 'protectedpagetext' => 'protectedpagetext',
2732 'protect-cantedit' => 'protect-cantedit',
2733 'deleteprotected' => 'deleteprotected',
2734 'badaccess-group0' => 'badaccess-group0',
2735 'badaccess-groups' => 'badaccess-groups',
2736 'titleprotected' => 'titleprotected',
2737 'nocreate-loggedin' => 'nocreate-loggedin',
2738 'nocreatetext' => 'nocreatetext',
2739 'movenologintext' => 'movenologintext',
2740 'movenotallowed' => 'movenotallowed',
2741 'confirmedittext' => 'confirmedittext',
2742 'blockedtext' => 'apierror-blocked',
2743 'autoblockedtext' => 'apierror-autoblocked',
2744 'systemblockedtext' => 'apierror-systemblocked',
2745 'actionthrottledtext' => 'apierror-ratelimited',
2746 'alreadyrolled' => 'alreadyrolled',
2747 'cantrollback' => 'cantrollback',
2748 'readonlytext' => 'readonlytext',
2749 'sessionfailure' => 'sessionfailure',
2750 'cannotdelete' => 'cannotdelete',
2751 'notanarticle' => 'apierror-missingtitle',
2752 'selfmove' => 'selfmove',
2753 'immobile_namespace' => 'apierror-immobilenamespace',
2754 'articleexists' => 'articleexists',
2755 'hookaborted' => 'hookaborted',
2756 'cantmove-titleprotected' => 'cantmove-titleprotected',
2757 'imagenocrossnamespace' => 'imagenocrossnamespace',
2758 'imagetypemismatch' => 'imagetypemismatch',
2759 'ip_range_invalid' => 'ip_range_invalid',
2760 'range_block_disabled' => 'range_block_disabled',
2761 'nosuchusershort' => 'nosuchusershort',
2762 'badipaddress' => 'badipaddress',
2763 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2764 'ipb_already_blocked' => 'ipb_already_blocked',
2765 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2766 'ipb_cant_unblock' => 'ipb_cant_unblock',
2767 'mailnologin' => 'apierror-cantsend',
2768 'ipbblocked' => 'ipbblocked',
2769 'ipbnounblockself' => 'ipbnounblockself',
2770 'usermaildisabled' => 'usermaildisabled',
2771 'blockedemailuser' => 'apierror-blockedfrommail',
2772 'notarget' => 'apierror-notarget',
2773 'noemail' => 'noemail',
2774 'rcpatroldisabled' => 'rcpatroldisabled',
2775 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2776 'delete-toobig' => 'delete-toobig',
2777 'movenotallowedfile' => 'movenotallowedfile',
2778 'userrights-no-interwiki' => 'userrights-no-interwiki',
2779 'userrights-nodatabase' => 'userrights-nodatabase',
2780 'nouserspecified' => 'nouserspecified',
2781 'noname' => 'noname',
2782 'summaryrequired' => 'apierror-summaryrequired',
2783 'import-rootpage-invalid' => 'import-rootpage-invalid',
2784 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2785 'readrequired' => 'apierror-readapidenied',
2786 'writedisabled' => 'apierror-noapiwrite',
2787 'writerequired' => 'apierror-writeapidenied',
2788 'missingparam' => 'apierror-missingparam',
2789 'invalidtitle' => 'apierror-invalidtitle',
2790 'nosuchpageid' => 'apierror-nosuchpageid',
2791 'nosuchrevid' => 'apierror-nosuchrevid',
2792 'nosuchuser' => 'nosuchusershort',
2793 'invaliduser' => 'apierror-invaliduser',
2794 'invalidexpiry' => 'apierror-invalidexpiry',
2795 'pastexpiry' => 'apierror-pastexpiry',
2796 'create-titleexists' => 'apierror-create-titleexists',
2797 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2798 'cantblock' => 'apierror-cantblock',
2799 'canthide' => 'apierror-canthide',
2800 'cantblock-email' => 'apierror-cantblock-email',
2801 'cantunblock' => 'apierror-permissiondenied-generic',
2802 'cannotundelete' => 'cannotundelete',
2803 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2804 'createonly-exists' => 'apierror-articleexists',
2805 'nocreate-missing' => 'apierror-missingtitle',
2806 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2807 'nosuchrcid' => 'apierror-nosuchrcid',
2808 'nosuchlogid' => 'apierror-nosuchlogid',
2809 'protect-invalidaction' => 'apierror-protect-invalidaction',
2810 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2811 'toofewexpiries' => 'apierror-toofewexpiries',
2812 'cantimport' => 'apierror-cantimport',
2813 'cantimport-upload' => 'apierror-cantimport-upload',
2814 'importnofile' => 'importnofile',
2815 'importuploaderrorsize' => 'importuploaderrorsize',
2816 'importuploaderrorpartial' => 'importuploaderrorpartial',
2817 'importuploaderrortemp' => 'importuploaderrortemp',
2818 'importcantopen' => 'importcantopen',
2819 'import-noarticle' => 'import-noarticle',
2820 'importbadinterwiki' => 'importbadinterwiki',
2821 'import-unknownerror' => 'apierror-import-unknownerror',
2822 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2823 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2824 'mustbeposted' => 'apierror-mustbeposted',
2825 'show' => 'apierror-show',
2826 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2827 'invalidoldimage' => 'apierror-invalidoldimage',
2828 'nodeleteablefile' => 'apierror-nodeleteablefile',
2829 'fileexists-forbidden' => 'fileexists-forbidden',
2830 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2831 'filerevert-badversion' => 'filerevert-badversion',
2832 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2833 'noimageredirect-logged' => 'apierror-noimageredirect',
2834 'spamdetected' => 'apierror-spamdetected',
2835 'contenttoobig' => 'apierror-contenttoobig',
2836 'noedit-anon' => 'apierror-noedit-anon',
2837 'noedit' => 'apierror-noedit',
2838 'wasdeleted' => 'apierror-pagedeleted',
2839 'blankpage' => 'apierror-emptypage',
2840 'editconflict' => 'editconflict',
2841 'hashcheckfailed' => 'apierror-badmd5',
2842 'missingtext' => 'apierror-notext',
2843 'emptynewsection' => 'apierror-emptynewsection',
2844 'revwrongpage' => 'apierror-revwrongpage',
2845 'undo-failure' => 'undo-failure',
2846 'content-not-allowed-here' => 'content-not-allowed-here',
2847 'edit-hook-aborted' => 'edit-hook-aborted',
2848 'edit-gone-missing' => 'edit-gone-missing',
2849 'edit-conflict' => 'edit-conflict',
2850 'edit-already-exists' => 'edit-already-exists',
2851 'invalid-file-key' => 'apierror-invalid-file-key',
2852 'nouploadmodule' => 'apierror-nouploadmodule',
2853 'uploaddisabled' => 'uploaddisabled',
2854 'copyuploaddisabled' => 'copyuploaddisabled',
2855 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2856 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2857 'filename-tooshort' => 'filename-tooshort',
2858 'filename-toolong' => 'filename-toolong',
2859 'illegal-filename' => 'illegal-filename',
2860 'filetype-missing' => 'filetype-missing',
2861 'mustbeloggedin' => 'apierror-mustbeloggedin',
2865 * @deprecated do not use
2866 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2867 * @return ApiMessage
2869 private function parseMsgInternal( $error ) {
2870 $msg = Message
::newFromSpecifier( $error );
2871 if ( !$msg instanceof IApiMessage
) {
2872 $key = $msg->getKey();
2873 if ( isset( self
::$messageMap[$key] ) ) {
2874 $params = $msg->getParams();
2875 array_unshift( $params, self
::$messageMap[$key] );
2877 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2879 $msg = ApiMessage
::create( $params );
2885 * Return the error message related to a certain array
2886 * @deprecated since 1.29
2887 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2888 * @return array [ 'code' => code, 'info' => info ]
2890 public function parseMsg( $error ) {
2891 wfDeprecated( __METHOD__
, '1.29' );
2892 // Check whether someone passed the whole array, instead of one element as
2893 // documented. This breaks if it's actually an array of fallback keys, but
2894 // that's long-standing misbehavior introduced in r87627 to incorrectly
2896 if ( is_array( $error ) ) {
2897 $first = reset( $error );
2898 if ( is_array( $first ) ) {
2899 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2904 $msg = $this->parseMsgInternal( $error );
2906 'code' => $msg->getApiCode(),
2907 'info' => ApiErrorFormatter
::stripMarkup(
2908 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2910 'data' => $msg->getApiData()
2915 * Output the error message related to a certain array
2916 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2917 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2918 * @throws ApiUsageException always
2920 public function dieUsageMsg( $error ) {
2921 wfDeprecated( __METHOD__
, '1.29' );
2922 $this->dieWithError( $this->parseMsgInternal( $error ) );
2926 * Will only set a warning instead of failing if the global $wgDebugAPI
2927 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2928 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2929 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2930 * @throws ApiUsageException
2933 public function dieUsageMsgOrDebug( $error ) {
2934 wfDeprecated( __METHOD__
, '1.29' );
2935 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2939 * Return the description message.
2941 * This is additional text to display on the help page after the summary.
2943 * @deprecated since 1.30
2944 * @return string|array|Message
2946 protected function getDescriptionMessage() {
2948 "apihelp-{$this->getModulePath()}-description",
2949 "apihelp-{$this->getModulePath()}-summary",
2957 * For really cool vim folding this needs to be at the end:
2958 * vim: foldmarker=@{,@} foldmethod=marker