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
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
49 /** (null|boolean|integer|string) Default value of the parameter. */
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI
= 1;
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace.
72 * - password: Any non-empty string. Input value is private or sensitive.
73 * <input type="password"> would be an appropriate HTML form field.
74 * - string: Any non-empty string, not expected to be very long or contain newlines.
75 * <input type="text"> would be an appropriate HTML form field.
76 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
77 * - text: Any non-empty string, expected to be very long or contain newlines.
78 * <textarea> would be an appropriate HTML form field.
79 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
80 * string 'now' representing the current timestamp. Will be returned in
82 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
83 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
84 * Cannot be used with PARAM_ISMULTI.
88 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
92 * (integer) Max value allowed for the parameter for users with the
93 * apihighlimits right, for PARAM_TYPE 'limit'.
97 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
100 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
101 const PARAM_ALLOW_DUPLICATES
= 6;
103 /** (boolean) Is the parameter deprecated (will show a warning)? */
104 const PARAM_DEPRECATED
= 7;
107 * (boolean) Is the parameter required?
110 const PARAM_REQUIRED
= 8;
113 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
116 const PARAM_RANGE_ENFORCE
= 9;
119 * (string|array|Message) Specify an alternative i18n documentation message
120 * for this parameter. Default is apihelp-{$path}-param-{$param}.
123 const PARAM_HELP_MSG
= 10;
126 * ((string|array|Message)[]) Specify additional i18n messages to append to
127 * the normal message for this parameter.
130 const PARAM_HELP_MSG_APPEND
= 11;
133 * (array) Specify additional information tags for the parameter. Value is
134 * an array of arrays, with the first member being the 'tag' for the info
135 * and the remaining members being the values. In the help, this is
136 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
137 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
140 const PARAM_HELP_MSG_INFO
= 12;
143 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
144 * those values to page titles which will be linked in the help.
147 const PARAM_VALUE_LINKS
= 13;
150 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
151 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
152 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
155 const PARAM_HELP_MSG_PER_VALUE
= 14;
158 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
159 * submodule paths. Default is to use all modules in
160 * $this->getModuleManager() in the group matching the parameter name.
163 const PARAM_SUBMODULE_MAP
= 15;
166 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
167 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
170 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
174 /** Fast query, standard limit. */
175 const LIMIT_BIG1
= 500;
176 /** Fast query, apihighlimits limit. */
177 const LIMIT_BIG2
= 5000;
178 /** Slow query, standard limit. */
179 const LIMIT_SML1
= 50;
180 /** Slow query, apihighlimits limit. */
181 const LIMIT_SML2
= 500;
184 * getAllowedParams() flag: When set, the result could take longer to generate,
185 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
188 const GET_VALUES_FOR_HELP
= 1;
190 /** @var array Maps extension paths to info arrays */
191 private static $extensionInfo = null;
194 private $mMainModule;
196 private $mModuleName, $mModulePrefix;
197 private $mSlaveDB = null;
198 private $mParamCache = array();
199 /** @var array|null|bool */
200 private $mModuleSource = false;
203 * @param ApiMain $mainModule
204 * @param string $moduleName Name of this module
205 * @param string $modulePrefix Prefix to use for parameter names
207 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
208 $this->mMainModule
= $mainModule;
209 $this->mModuleName
= $moduleName;
210 $this->mModulePrefix
= $modulePrefix;
212 if ( !$this->isMain() ) {
213 $this->setContext( $mainModule->getContext() );
217 /************************************************************************//**
218 * @name Methods to implement
223 * Evaluates the parameters, performs the requested query, and sets up
224 * the result. Concrete implementations of ApiBase must override this
225 * method to provide whatever functionality their module offers.
226 * Implementations must not produce any output on their own and are not
227 * expected to handle any errors.
229 * The execute() method will be invoked directly by ApiMain immediately
230 * before the result of the module is output. Aside from the
231 * constructor, implementations should assume that no other methods
232 * will be called externally on the module before the result is
235 * The result data should be stored in the ApiResult object available
236 * through getResult().
238 abstract public function execute();
241 * Get the module manager, or null if this module has no sub-modules
243 * @return ApiModuleManager
245 public function getModuleManager() {
250 * If the module may only be used with a certain format module,
251 * it should override this method to return an instance of that formatter.
252 * A value of null means the default format will be used.
253 * @note Do not use this just because you don't want to support non-json
254 * formats. This should be used only when there is a fundamental
255 * requirement for a specific format.
256 * @return mixed Instance of a derived class of ApiFormatBase, or null
258 public function getCustomPrinter() {
263 * Returns usage examples for this module.
265 * Return value has query strings as keys, with values being either strings
266 * (message key), arrays (message key + parameter), or Message objects.
268 * Do not call this base class implementation when overriding this method.
273 protected function getExamplesMessages() {
274 // Fall back to old non-localised method
277 $examples = $this->getExamples();
279 if ( !is_array( $examples ) ) {
280 $examples = array( $examples );
281 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
282 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
283 !preg_match( '/^\s*api\.php\?/', $examples[0] )
285 // Fix up the ugly "even numbered elements are description, odd
286 // numbered elemts are the link" format (see doc for self::getExamples)
288 $examplesCount = count( $examples );
289 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
290 $tmp[$examples[$i +
1]] = $examples[$i];
295 foreach ( $examples as $k => $v ) {
296 if ( is_numeric( $k ) ) {
301 $msg = self
::escapeWikiText( $v );
302 if ( is_array( $msg ) ) {
303 $msg = join( " ", $msg );
307 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
308 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
316 * Return links to more detailed help pages about the module.
317 * @since 1.25, returning boolean false is deprecated
318 * @return string|array
320 public function getHelpUrls() {
325 * Returns an array of allowed parameters (parameter name) => (default
326 * value) or (parameter name) => (array with PARAM_* constants as keys)
327 * Don't call this function directly: use getFinalParams() to allow
328 * hooks to modify parameters as needed.
330 * Some derived classes may choose to handle an integer $flags parameter
331 * in the overriding methods. Callers of this method can pass zero or
332 * more OR-ed flags like GET_VALUES_FOR_HELP.
336 protected function getAllowedParams( /* $flags = 0 */ ) {
337 // int $flags is not declared because it causes "Strict standards"
338 // warning. Most derived classes do not implement it.
343 * Indicates if this module needs maxlag to be checked
346 public function shouldCheckMaxlag() {
351 * Indicates whether this module requires read rights
354 public function isReadMode() {
359 * Indicates whether this module requires write mode
362 public function isWriteMode() {
367 * Indicates whether this module must be called with a POST request
370 public function mustBePosted() {
371 return $this->needsToken() !== false;
375 * Indicates whether this module is deprecated
379 public function isDeprecated() {
384 * Indicates whether this module is "internal"
385 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
389 public function isInternal() {
394 * Returns the token type this module requires in order to execute.
396 * Modules are strongly encouraged to use the core 'csrf' type unless they
397 * have specialized security needs. If the token type is not one of the
398 * core types, you must use the ApiQueryTokensRegisterTypes hook to
401 * Returning a non-falsey value here will force the addition of an
402 * appropriate 'token' parameter in self::getFinalParams(). Also,
403 * self::mustBePosted() must return true when tokens are used.
405 * In previous versions of MediaWiki, true was a valid return value.
406 * Returning true will generate errors indicating that the API module needs
409 * @return string|false
411 public function needsToken() {
416 * Fetch the salt used in the Web UI corresponding to this module.
418 * Only override this if the Web UI uses a token with a non-constant salt.
421 * @param array $params All supplied parameters for the module
422 * @return string|array|null
424 protected function getWebUITokenSalt( array $params ) {
429 * Returns data for HTTP conditional request mechanisms.
432 * @param string $condition Condition being queried:
433 * - last-modified: Return a timestamp representing the maximum of the
434 * last-modified dates for all resources involved in the request. See
435 * RFC 7232 § 2.2 for semantics.
436 * - etag: Return an entity-tag representing the state of all resources involved
437 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
438 * @return string|boolean|null As described above, or null if no value is available.
440 public function getConditionalRequestData( $condition ) {
446 /************************************************************************//**
447 * @name Data access methods
452 * Get the name of the module being executed by this instance
455 public function getModuleName() {
456 return $this->mModuleName
;
460 * Get parameter prefix (usually two letters or an empty string).
463 public function getModulePrefix() {
464 return $this->mModulePrefix
;
468 * Get the main module
471 public function getMain() {
472 return $this->mMainModule
;
476 * Returns true if this module is the main module ($this === $this->mMainModule),
480 public function isMain() {
481 return $this === $this->mMainModule
;
485 * Get the parent of this module
487 * @return ApiBase|null
489 public function getParent() {
490 return $this->isMain() ?
null : $this->getMain();
494 * Returns true if the current request breaks the same-origin policy.
496 * For example, json with callbacks.
498 * https://en.wikipedia.org/wiki/Same-origin_policy
503 public function lacksSameOriginSecurity() {
504 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
508 * Get the path to this module
513 public function getModulePath() {
514 if ( $this->isMain() ) {
516 } elseif ( $this->getParent()->isMain() ) {
517 return $this->getModuleName();
519 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
524 * Get a module from its module path
527 * @param string $path
528 * @return ApiBase|null
529 * @throws UsageException
531 public function getModuleFromPath( $path ) {
532 $module = $this->getMain();
533 if ( $path === 'main' ) {
537 $parts = explode( '+', $path );
538 if ( count( $parts ) === 1 ) {
539 // In case the '+' was typed into URL, it resolves as a space
540 $parts = explode( ' ', $path );
543 $count = count( $parts );
544 for ( $i = 0; $i < $count; $i++
) {
546 $manager = $parent->getModuleManager();
547 if ( $manager === null ) {
548 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
549 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
551 $module = $manager->getModule( $parts[$i] );
553 if ( $module === null ) {
554 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
556 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
566 * Get the result object
569 public function getResult() {
570 // Main module has getResult() method overridden
571 // Safety - avoid infinite loop:
572 if ( $this->isMain() ) {
573 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
576 return $this->getMain()->getResult();
580 * Get the error formatter
581 * @return ApiErrorFormatter
583 public function getErrorFormatter() {
584 // Main module has getErrorFormatter() method overridden
585 // Safety - avoid infinite loop:
586 if ( $this->isMain() ) {
587 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
590 return $this->getMain()->getErrorFormatter();
594 * Gets a default slave database connection object
595 * @return DatabaseBase
597 protected function getDB() {
598 if ( !isset( $this->mSlaveDB
) ) {
599 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
602 return $this->mSlaveDB
;
606 * Get the continuation manager
607 * @return ApiContinuationManager|null
609 public function getContinuationManager() {
610 // Main module has getContinuationManager() method overridden
611 // Safety - avoid infinite loop:
612 if ( $this->isMain() ) {
613 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
616 return $this->getMain()->getContinuationManager();
620 * Set the continuation manager
621 * @param ApiContinuationManager|null
623 public function setContinuationManager( $manager ) {
624 // Main module has setContinuationManager() method overridden
625 // Safety - avoid infinite loop:
626 if ( $this->isMain() ) {
627 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
630 $this->getMain()->setContinuationManager( $manager );
635 /************************************************************************//**
636 * @name Parameter handling
641 * Indicate if the module supports dynamically-determined parameters that
642 * cannot be included in self::getAllowedParams().
643 * @return string|array|Message|null Return null if the module does not
644 * support additional dynamic parameters, otherwise return a message
647 public function dynamicParameterDocumentation() {
652 * This method mangles parameter name based on the prefix supplied to the constructor.
653 * Override this method to change parameter name during runtime
654 * @param string $paramName Parameter name
655 * @return string Prefixed parameter name
657 public function encodeParamName( $paramName ) {
658 return $this->mModulePrefix
. $paramName;
662 * Using getAllowedParams(), this function makes an array of the values
663 * provided by the user, with key being the name of the variable, and
664 * value - validated value from user or default. limits will not be
665 * parsed if $parseLimit is set to false; use this when the max
666 * limit is not definitive yet, e.g. when getting revisions.
667 * @param bool $parseLimit True by default
670 public function extractRequestParams( $parseLimit = true ) {
671 // Cache parameters, for performance and to avoid bug 24564.
672 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
673 $params = $this->getFinalParams();
676 if ( $params ) { // getFinalParams() can return false
677 foreach ( $params as $paramName => $paramSettings ) {
678 $results[$paramName] = $this->getParameterFromSettings(
679 $paramName, $paramSettings, $parseLimit );
682 $this->mParamCache
[$parseLimit] = $results;
685 return $this->mParamCache
[$parseLimit];
689 * Get a value for the given parameter
690 * @param string $paramName Parameter name
691 * @param bool $parseLimit See extractRequestParams()
692 * @return mixed Parameter value
694 protected function getParameter( $paramName, $parseLimit = true ) {
695 $params = $this->getFinalParams();
696 $paramSettings = $params[$paramName];
698 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
702 * Die if none or more than one of a certain set of parameters is set and not false.
704 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
705 * @param string $required,... Names of parameters of which exactly one must be set
707 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
708 $required = func_get_args();
709 array_shift( $required );
710 $p = $this->getModulePrefix();
712 $intersection = array_intersect( array_keys( array_filter( $params,
713 array( $this, "parameterNotEmpty" ) ) ), $required );
715 if ( count( $intersection ) > 1 ) {
717 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
719 } elseif ( count( $intersection ) == 0 ) {
721 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
728 * Die if more than one of a certain set of parameters is set and not false.
730 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
731 * @param string $required,... Names of parameters of which at most one must be set
733 public function requireMaxOneParameter( $params, $required /*...*/ ) {
734 $required = func_get_args();
735 array_shift( $required );
736 $p = $this->getModulePrefix();
738 $intersection = array_intersect( array_keys( array_filter( $params,
739 array( $this, "parameterNotEmpty" ) ) ), $required );
741 if ( count( $intersection ) > 1 ) {
743 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
750 * Die if none of a certain set of parameters is set and not false.
753 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
754 * @param string $required,... Names of parameters of which at least one must be set
756 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
757 $required = func_get_args();
758 array_shift( $required );
759 $p = $this->getModulePrefix();
761 $intersection = array_intersect(
762 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
766 if ( count( $intersection ) == 0 ) {
767 $this->dieUsage( "At least one of the parameters {$p}" .
768 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
773 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
775 * @param object $x Parameter to check is not null/false
778 private function parameterNotEmpty( $x ) {
779 return !is_null( $x ) && $x !== false;
783 * Get a WikiPage object from a title or pageid param, if possible.
784 * Can die, if no param is set or if the title or page id is not valid.
786 * @param array $params
787 * @param bool|string $load Whether load the object's state from the database:
788 * - false: don't load (if the pageid is given, it will still be loaded)
789 * - 'fromdb': load from a slave database
790 * - 'fromdbmaster': load from the master database
793 public function getTitleOrPageId( $params, $load = false ) {
794 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
797 if ( isset( $params['title'] ) ) {
798 $titleObj = Title
::newFromText( $params['title'] );
799 if ( !$titleObj ||
$titleObj->isExternal() ) {
800 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
802 if ( !$titleObj->canExist() ) {
803 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
805 $pageObj = WikiPage
::factory( $titleObj );
806 if ( $load !== false ) {
807 $pageObj->loadPageData( $load );
809 } elseif ( isset( $params['pageid'] ) ) {
810 if ( $load === false ) {
813 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
815 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
823 * Return true if we're to watch the page, false if not, null if no change.
824 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
825 * @param Title $titleObj The page under consideration
826 * @param string $userOption The user option to consider when $watchlist=preferences.
827 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
830 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
832 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
834 switch ( $watchlist ) {
842 # If the user is already watching, don't bother checking
843 if ( $userWatching ) {
846 # If no user option was passed, use watchdefault and watchcreations
847 if ( is_null( $userOption ) ) {
848 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
849 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
852 # Watch the article based on the user preference
853 return $this->getUser()->getBoolOption( $userOption );
856 return $userWatching;
859 return $userWatching;
864 * Using the settings determine the value for the given parameter
866 * @param string $paramName Parameter name
867 * @param array|mixed $paramSettings Default value or an array of settings
868 * using PARAM_* constants.
869 * @param bool $parseLimit Parse limit?
870 * @return mixed Parameter value
872 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
873 // Some classes may decide to change parameter names
874 $encParamName = $this->encodeParamName( $paramName );
876 if ( !is_array( $paramSettings ) ) {
877 $default = $paramSettings;
879 $type = gettype( $paramSettings );
884 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
885 ?
$paramSettings[self
::PARAM_DFLT
]
887 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
888 ?
$paramSettings[self
::PARAM_ISMULTI
]
890 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
891 ?
$paramSettings[self
::PARAM_TYPE
]
893 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
894 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
896 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
897 ?
$paramSettings[self
::PARAM_DEPRECATED
]
899 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
900 ?
$paramSettings[self
::PARAM_REQUIRED
]
903 // When type is not given, and no choices, the type is the same as $default
904 if ( !isset( $type ) ) {
905 if ( isset( $default ) ) {
906 $type = gettype( $default );
908 $type = 'NULL'; // allow everything
913 if ( $type == 'boolean' ) {
914 if ( isset( $default ) && $default !== false ) {
915 // Having a default value of anything other than 'false' is not allowed
918 "Boolean param $encParamName's default is set to '$default'. " .
919 "Boolean parameters must default to false."
923 $value = $this->getMain()->getCheck( $encParamName );
924 } elseif ( $type == 'upload' ) {
925 if ( isset( $default ) ) {
926 // Having a default value is not allowed
929 "File upload param $encParamName's default is set to " .
930 "'$default'. File upload parameters may not have a default." );
933 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
935 $value = $this->getMain()->getUpload( $encParamName );
936 if ( !$value->exists() ) {
937 // This will get the value without trying to normalize it
938 // (because trying to normalize a large binary file
939 // accidentally uploaded as a field fails spectacularly)
940 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
941 if ( $value !== null ) {
943 "File upload param $encParamName is not a file upload; " .
944 "be sure to use multipart/form-data for your POST and include " .
945 "a filename in the Content-Disposition header.",
946 "badupload_{$encParamName}"
951 $value = $this->getMain()->getVal( $encParamName, $default );
953 if ( isset( $value ) && $type == 'namespace' ) {
954 $type = MWNamespace
::getValidNamespaces();
956 if ( isset( $value ) && $type == 'submodule' ) {
957 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
958 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
960 $type = $this->getModuleManager()->getNames( $paramName );
965 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
966 $value = $this->parseMultiValue(
970 is_array( $type ) ?
$type : null
974 // More validation only when choices were not given
975 // choices were validated in parseMultiValue()
976 if ( isset( $value ) ) {
977 if ( !is_array( $type ) ) {
979 case 'NULL': // nothing to do
984 if ( $required && $value === '' ) {
985 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
988 case 'integer': // Force everything using intval() and optionally validate limits
989 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
990 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
991 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
992 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
994 if ( is_array( $value ) ) {
995 $value = array_map( 'intval', $value );
996 if ( !is_null( $min ) ||
!is_null( $max ) ) {
997 foreach ( $value as &$v ) {
998 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1002 $value = intval( $value );
1003 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1004 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1009 if ( !$parseLimit ) {
1010 // Don't do any validation whatsoever
1013 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1014 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1018 "MAX1 or MAX2 are not defined for the limit $encParamName"
1022 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1024 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1025 if ( $value == 'max' ) {
1026 $value = $this->getMain()->canApiHighLimits()
1027 ?
$paramSettings[self
::PARAM_MAX2
]
1028 : $paramSettings[self
::PARAM_MAX
];
1029 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1031 $value = intval( $value );
1032 $this->validateLimit(
1036 $paramSettings[self
::PARAM_MAX
],
1037 $paramSettings[self
::PARAM_MAX2
]
1043 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1047 if ( is_array( $value ) ) {
1048 foreach ( $value as $key => $val ) {
1049 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1052 $value = $this->validateTimestamp( $value, $encParamName );
1056 if ( is_array( $value ) ) {
1057 foreach ( $value as $key => $val ) {
1058 $value[$key] = $this->validateUser( $val, $encParamName );
1061 $value = $this->validateUser( $value, $encParamName );
1064 case 'upload': // nothing to do
1067 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1071 // Throw out duplicates if requested
1072 if ( !$dupes && is_array( $value ) ) {
1073 $value = array_unique( $value );
1076 // Set a warning if a deprecated parameter has been passed
1077 if ( $deprecated && $value !== false ) {
1078 $this->setWarning( "The $encParamName parameter has been deprecated." );
1080 $feature = $encParamName;
1082 while ( !$m->isMain() ) {
1083 $p = $m->getParent();
1084 $name = $m->getModuleName();
1085 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1086 $feature = "{$param}={$name}&{$feature}";
1089 $this->logFeatureUsage( $feature );
1091 } elseif ( $required ) {
1092 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1099 * Return an array of values that were given in a 'a|b|c' notation,
1100 * after it optionally validates them against the list allowed values.
1102 * @param string $valueName The name of the parameter (for error
1104 * @param mixed $value The value being parsed
1105 * @param bool $allowMultiple Can $value contain more than one value
1107 * @param string[]|null $allowedValues An array of values to check against. If
1108 * null, all values are accepted.
1109 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1111 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1112 if ( trim( $value ) === '' && $allowMultiple ) {
1116 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1117 // because it unstubs $wgUser
1118 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1119 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1123 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1124 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1125 "the limit is $sizeLimit" );
1128 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1129 // Bug 33482 - Allow entries with | in them for non-multiple values
1130 if ( in_array( $value, $allowedValues, true ) ) {
1134 $possibleValues = is_array( $allowedValues )
1135 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1138 "Only one $possibleValues is allowed for parameter '$valueName'",
1139 "multival_$valueName"
1143 if ( is_array( $allowedValues ) ) {
1144 // Check for unknown values
1145 $unknown = array_diff( $valuesList, $allowedValues );
1146 if ( count( $unknown ) ) {
1147 if ( $allowMultiple ) {
1148 $s = count( $unknown ) > 1 ?
's' : '';
1149 $vals = implode( ", ", $unknown );
1150 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1153 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1154 "unknown_$valueName"
1158 // Now throw them out
1159 $valuesList = array_intersect( $valuesList, $allowedValues );
1162 return $allowMultiple ?
$valuesList : $valuesList[0];
1166 * Validate the value against the minimum and user/bot maximum limits.
1167 * Prints usage info on failure.
1168 * @param string $paramName Parameter name
1169 * @param int $value Parameter value
1170 * @param int|null $min Minimum value
1171 * @param int|null $max Maximum value for users
1172 * @param int $botMax Maximum value for sysops/bots
1173 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1175 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1176 $enforceLimits = false
1178 if ( !is_null( $min ) && $value < $min ) {
1179 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1180 $this->warnOrDie( $msg, $enforceLimits );
1184 // Minimum is always validated, whereas maximum is checked only if not
1185 // running in internal call mode
1186 if ( $this->getMain()->isInternalMode() ) {
1190 // Optimization: do not check user's bot status unless really needed -- skips db query
1191 // assumes $botMax >= $max
1192 if ( !is_null( $max ) && $value > $max ) {
1193 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1194 if ( $value > $botMax ) {
1195 $msg = $this->encodeParamName( $paramName ) .
1196 " may not be over $botMax (set to $value) for bots or sysops";
1197 $this->warnOrDie( $msg, $enforceLimits );
1201 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1202 $this->warnOrDie( $msg, $enforceLimits );
1209 * Validate and normalize of parameters of type 'timestamp'
1210 * @param string $value Parameter value
1211 * @param string $encParamName Parameter name
1212 * @return string Validated and normalized parameter
1214 protected function validateTimestamp( $value, $encParamName ) {
1215 // Confusing synonyms for the current time accepted by wfTimestamp()
1216 // (wfTimestamp() also accepts various non-strings and the string of 14
1217 // ASCII NUL bytes, but those can't get here)
1219 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1221 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1222 ' If for some reason you need to explicitly specify the current time without' .
1223 ' calculating it client-side, use "now".'
1225 return wfTimestamp( TS_MW
);
1228 // Explicit synonym for the current time
1229 if ( $value === 'now' ) {
1230 return wfTimestamp( TS_MW
);
1233 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1234 if ( $unixTimestamp === false ) {
1236 "Invalid value '$value' for timestamp parameter $encParamName",
1237 "badtimestamp_{$encParamName}"
1241 return wfTimestamp( TS_MW
, $unixTimestamp );
1245 * Validate the supplied token.
1248 * @param string $token Supplied token
1249 * @param array $params All supplied parameters for the module
1251 * @throws MWException
1253 final public function validateToken( $token, array $params ) {
1254 $tokenType = $this->needsToken();
1255 $salts = ApiQueryTokens
::getTokenTypeSalts();
1256 if ( !isset( $salts[$tokenType] ) ) {
1257 throw new MWException(
1258 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1259 'without registering it'
1263 if ( $this->getUser()->matchEditToken(
1271 $webUiSalt = $this->getWebUITokenSalt( $params );
1272 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1284 * Validate and normalize of parameters of type 'user'
1285 * @param string $value Parameter value
1286 * @param string $encParamName Parameter name
1287 * @return string Validated and normalized parameter
1289 private function validateUser( $value, $encParamName ) {
1290 $title = Title
::makeTitleSafe( NS_USER
, $value );
1291 if ( $title === null ) {
1293 "Invalid value '$value' for user parameter $encParamName",
1294 "baduser_{$encParamName}"
1298 return $title->getText();
1303 /************************************************************************//**
1304 * @name Utility methods
1309 * Set a watch (or unwatch) based the based on a watchlist parameter.
1310 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1311 * @param Title $titleObj The article's title to change
1312 * @param string $userOption The user option to consider when $watch=preferences
1314 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1315 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1316 if ( $value === null ) {
1320 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1324 * Truncate an array to a certain length.
1325 * @param array $arr Array to truncate
1326 * @param int $limit Maximum length
1327 * @return bool True if the array was truncated, false otherwise
1329 public static function truncateArray( &$arr, $limit ) {
1331 while ( count( $arr ) > $limit ) {
1340 * Gets the user for whom to get the watchlist
1342 * @param array $params
1345 public function getWatchlistUser( $params ) {
1346 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1347 $user = User
::newFromName( $params['owner'], false );
1348 if ( !( $user && $user->getId() ) ) {
1349 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1351 $token = $user->getOption( 'watchlisttoken' );
1352 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1354 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1359 if ( !$this->getUser()->isLoggedIn() ) {
1360 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1362 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1363 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1365 $user = $this->getUser();
1372 * A subset of wfEscapeWikiText for BC texts
1375 * @param string|array $v
1376 * @return string|array
1378 private static function escapeWikiText( $v ) {
1379 if ( is_array( $v ) ) {
1380 return array_map( 'self::escapeWikiText', $v );
1382 return strtr( $v, array(
1383 '__' => '__', '{' => '{', '}' => '}',
1384 '[[Category:' => '[[:Category:',
1385 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1391 * Create a Message from a string or array
1393 * A string is used as a message key. An array has the message key as the
1394 * first value and message parameters as subsequent values.
1397 * @param string|array|Message $msg
1398 * @param IContextSource $context
1399 * @param array $params
1400 * @return Message|null
1402 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1403 if ( is_string( $msg ) ) {
1404 $msg = wfMessage( $msg );
1405 } elseif ( is_array( $msg ) ) {
1406 $msg = call_user_func_array( 'wfMessage', $msg );
1408 if ( !$msg instanceof Message
) {
1412 $msg->setContext( $context );
1414 $msg->params( $params );
1422 /************************************************************************//**
1423 * @name Warning and error reporting
1428 * Set warning section for this module. Users should monitor this
1429 * section to notice any changes in API. Multiple calls to this
1430 * function will result in the warning messages being separated by
1432 * @param string $warning Warning message
1434 public function setWarning( $warning ) {
1435 $msg = new ApiRawMessage( $warning, 'warning' );
1436 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1440 * Adds a warning to the output, else dies
1442 * @param string $msg Message to show as a warning, or error message if dying
1443 * @param bool $enforceLimits Whether this is an enforce (die)
1445 private function warnOrDie( $msg, $enforceLimits = false ) {
1446 if ( $enforceLimits ) {
1447 $this->dieUsage( $msg, 'integeroutofrange' );
1450 $this->setWarning( $msg );
1454 * Throw a UsageException, which will (if uncaught) call the main module's
1455 * error handler and die with an error message.
1457 * @param string $description One-line human-readable description of the
1458 * error condition, e.g., "The API requires a valid action parameter"
1459 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1460 * automated identification of the error, e.g., 'unknown_action'
1461 * @param int $httpRespCode HTTP response code
1462 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1463 * @throws UsageException always
1465 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1466 throw new UsageException(
1468 $this->encodeParamName( $errorCode ),
1475 * Throw a UsageException, which will (if uncaught) call the main module's
1476 * error handler and die with an error message including block info.
1479 * @param Block $block The block used to generate the UsageException
1480 * @throws UsageException always
1482 public function dieBlocked( Block
$block ) {
1483 // Die using the appropriate message depending on block type
1484 if ( $block->getType() == Block
::TYPE_AUTO
) {
1486 'Your IP address has been blocked automatically, because it was used by a blocked user',
1489 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) )
1493 'You have been blocked from editing',
1496 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) )
1502 * Get error (as code, string) from a Status object.
1505 * @param Status $status
1506 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1507 * @return array Array of code and error string
1508 * @throws MWException
1510 public function getErrorFromStatus( $status, &$extraData = null ) {
1511 if ( $status->isGood() ) {
1512 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1515 $errors = $status->getErrorsArray();
1517 // No errors? Assume the warnings should be treated as errors
1518 $errors = $status->getWarningsArray();
1521 // Still no errors? Punt
1522 $errors = array( array( 'unknownerror-nocode' ) );
1525 // Cannot use dieUsageMsg() because extensions might return custom
1527 if ( $errors[0] instanceof Message
) {
1529 if ( $msg instanceof IApiMessage
) {
1530 $extraData = $msg->getApiData();
1531 $code = $msg->getApiCode();
1533 $code = $msg->getKey();
1536 $code = array_shift( $errors[0] );
1537 $msg = wfMessage( $code, $errors[0] );
1539 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1540 // Translate message to code, for backwards compatibility
1541 $code = ApiBase
::$messageMap[$code]['code'];
1544 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1548 * Throw a UsageException based on the errors in the Status object.
1551 * @param Status $status
1552 * @throws UsageException always
1554 public function dieStatus( $status ) {
1556 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1557 $this->dieUsage( $msg, $code, 0, $extraData );
1560 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1562 * Array that maps message keys to error messages. $1 and friends are replaced.
1564 public static $messageMap = array(
1565 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1566 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1567 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1569 // Messages from Title::getUserPermissionsErrors()
1570 'ns-specialprotected' => array(
1571 'code' => 'unsupportednamespace',
1572 'info' => "Pages in the Special namespace can't be edited"
1574 'protectedinterface' => array(
1575 'code' => 'protectednamespace-interface',
1576 'info' => "You're not allowed to edit interface messages"
1578 'namespaceprotected' => array(
1579 'code' => 'protectednamespace',
1580 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1582 'customcssprotected' => array(
1583 'code' => 'customcssprotected',
1584 'info' => "You're not allowed to edit custom CSS pages"
1586 'customjsprotected' => array(
1587 'code' => 'customjsprotected',
1588 'info' => "You're not allowed to edit custom JavaScript pages"
1590 'cascadeprotected' => array(
1591 'code' => 'cascadeprotected',
1592 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1594 'protectedpagetext' => array(
1595 'code' => 'protectedpage',
1596 'info' => "The \"\$1\" right is required to edit this page"
1598 'protect-cantedit' => array(
1599 'code' => 'cantedit',
1600 'info' => "You can't protect this page because you can't edit it"
1602 'deleteprotected' => array(
1603 'code' => 'cantedit',
1604 'info' => "You can't delete this page because it has been protected"
1606 'badaccess-group0' => array(
1607 'code' => 'permissiondenied',
1608 'info' => "Permission denied"
1609 ), // Generic permission denied message
1610 'badaccess-groups' => array(
1611 'code' => 'permissiondenied',
1612 'info' => "Permission denied"
1614 'titleprotected' => array(
1615 'code' => 'protectedtitle',
1616 'info' => "This title has been protected from creation"
1618 'nocreate-loggedin' => array(
1619 'code' => 'cantcreate',
1620 'info' => "You don't have permission to create new pages"
1622 'nocreatetext' => array(
1623 'code' => 'cantcreate-anon',
1624 'info' => "Anonymous users can't create new pages"
1626 'movenologintext' => array(
1627 'code' => 'cantmove-anon',
1628 'info' => "Anonymous users can't move pages"
1630 'movenotallowed' => array(
1631 'code' => 'cantmove',
1632 'info' => "You don't have permission to move pages"
1634 'confirmedittext' => array(
1635 'code' => 'confirmemail',
1636 'info' => "You must confirm your email address before you can edit"
1638 'blockedtext' => array(
1639 'code' => 'blocked',
1640 'info' => "You have been blocked from editing"
1642 'autoblockedtext' => array(
1643 'code' => 'autoblocked',
1644 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1647 // Miscellaneous interface messages
1648 'actionthrottledtext' => array(
1649 'code' => 'ratelimited',
1650 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1652 'alreadyrolled' => array(
1653 'code' => 'alreadyrolled',
1654 'info' => "The page you tried to rollback was already rolled back"
1656 'cantrollback' => array(
1657 'code' => 'onlyauthor',
1658 'info' => "The page you tried to rollback only has one author"
1660 'readonlytext' => array(
1661 'code' => 'readonly',
1662 'info' => "The wiki is currently in read-only mode"
1664 'sessionfailure' => array(
1665 'code' => 'badtoken',
1666 'info' => "Invalid token" ),
1667 'cannotdelete' => array(
1668 'code' => 'cantdelete',
1669 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1671 'notanarticle' => array(
1672 'code' => 'missingtitle',
1673 'info' => "The page you requested doesn't exist"
1675 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1677 'immobile_namespace' => array(
1678 'code' => 'immobilenamespace',
1679 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1681 'articleexists' => array(
1682 'code' => 'articleexists',
1683 'info' => "The destination article already exists and is not a redirect to the source article"
1685 'protectedpage' => array(
1686 'code' => 'protectedpage',
1687 'info' => "You don't have permission to perform this move"
1689 'hookaborted' => array(
1690 'code' => 'hookaborted',
1691 'info' => "The modification you tried to make was aborted by an extension hook"
1693 'cantmove-titleprotected' => array(
1694 'code' => 'protectedtitle',
1695 'info' => "The destination article has been protected from creation"
1697 'imagenocrossnamespace' => array(
1698 'code' => 'nonfilenamespace',
1699 'info' => "Can't move a file to a non-file namespace"
1701 'imagetypemismatch' => array(
1702 'code' => 'filetypemismatch',
1703 'info' => "The new file extension doesn't match its type"
1705 // 'badarticleerror' => shouldn't happen
1706 // 'badtitletext' => shouldn't happen
1707 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1708 'range_block_disabled' => array(
1709 'code' => 'rangedisabled',
1710 'info' => "Blocking IP ranges has been disabled"
1712 'nosuchusershort' => array(
1713 'code' => 'nosuchuser',
1714 'info' => "The user you specified doesn't exist"
1716 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1717 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1718 'ipb_already_blocked' => array(
1719 'code' => 'alreadyblocked',
1720 'info' => "The user you tried to block was already blocked"
1722 'ipb_blocked_as_range' => array(
1723 'code' => 'blockedasrange',
1724 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1726 'ipb_cant_unblock' => array(
1727 'code' => 'cantunblock',
1728 'info' => "The block you specified was not found. It may have been unblocked already"
1730 'mailnologin' => array(
1731 'code' => 'cantsend',
1732 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1734 'ipbblocked' => array(
1735 'code' => 'ipbblocked',
1736 'info' => 'You cannot block or unblock users while you are yourself blocked'
1738 'ipbnounblockself' => array(
1739 'code' => 'ipbnounblockself',
1740 'info' => 'You are not allowed to unblock yourself'
1742 'usermaildisabled' => array(
1743 'code' => 'usermaildisabled',
1744 'info' => "User email has been disabled"
1746 'blockedemailuser' => array(
1747 'code' => 'blockedfrommail',
1748 'info' => "You have been blocked from sending email"
1750 'notarget' => array(
1751 'code' => 'notarget',
1752 'info' => "You have not specified a valid target for this action"
1755 'code' => 'noemail',
1756 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1758 'rcpatroldisabled' => array(
1759 'code' => 'patroldisabled',
1760 'info' => "Patrolling is disabled on this wiki"
1762 'markedaspatrollederror-noautopatrol' => array(
1763 'code' => 'noautopatrol',
1764 'info' => "You don't have permission to patrol your own changes"
1766 'delete-toobig' => array(
1767 'code' => 'bigdelete',
1768 'info' => "You can't delete this page because it has more than \$1 revisions"
1770 'movenotallowedfile' => array(
1771 'code' => 'cantmovefile',
1772 'info' => "You don't have permission to move files"
1774 'userrights-no-interwiki' => array(
1775 'code' => 'nointerwikiuserrights',
1776 'info' => "You don't have permission to change user rights on other wikis"
1778 'userrights-nodatabase' => array(
1779 'code' => 'nosuchdatabase',
1780 'info' => "Database \"\$1\" does not exist or is not local"
1782 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1783 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1784 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1785 'import-rootpage-invalid' => array(
1786 'code' => 'import-rootpage-invalid',
1787 'info' => 'Root page is an invalid title'
1789 'import-rootpage-nosubpage' => array(
1790 'code' => 'import-rootpage-nosubpage',
1791 'info' => 'Namespace "$1" of the root page does not allow subpages'
1794 // API-specific messages
1795 'readrequired' => array(
1796 'code' => 'readapidenied',
1797 'info' => "You need read permission to use this module"
1799 'writedisabled' => array(
1800 'code' => 'noapiwrite',
1801 'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file"
1803 'writerequired' => array(
1804 'code' => 'writeapidenied',
1805 'info' => "You're not allowed to edit this wiki through the API"
1807 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1808 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1809 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1810 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1811 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1812 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1813 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1814 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1815 'create-titleexists' => array(
1816 'code' => 'create-titleexists',
1817 'info' => "Existing titles can't be protected with 'create'"
1819 'missingtitle-createonly' => array(
1820 'code' => 'missingtitle-createonly',
1821 'info' => "Missing titles can only be protected with 'create'"
1823 'cantblock' => array( 'code' => 'cantblock',
1824 'info' => "You don't have permission to block users"
1826 'canthide' => array(
1827 'code' => 'canthide',
1828 'info' => "You don't have permission to hide user names from the block log"
1830 'cantblock-email' => array(
1831 'code' => 'cantblock-email',
1832 'info' => "You don't have permission to block users from sending email through the wiki"
1834 'unblock-notarget' => array(
1835 'code' => 'notarget',
1836 'info' => "Either the id or the user parameter must be set"
1838 'unblock-idanduser' => array(
1839 'code' => 'idanduser',
1840 'info' => "The id and user parameters can't be used together"
1842 'cantunblock' => array(
1843 'code' => 'permissiondenied',
1844 'info' => "You don't have permission to unblock users"
1846 'cannotundelete' => array(
1847 'code' => 'cantundelete',
1848 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1850 'permdenied-undelete' => array(
1851 'code' => 'permissiondenied',
1852 'info' => "You don't have permission to restore deleted revisions"
1854 'createonly-exists' => array(
1855 'code' => 'articleexists',
1856 'info' => "The article you tried to create has been created already"
1858 'nocreate-missing' => array(
1859 'code' => 'missingtitle',
1860 'info' => "The article you tried to edit doesn't exist"
1862 'cantchangecontentmodel' => array(
1863 'code' => 'cantchangecontentmodel',
1864 'info' => "You don't have permission to change the content model of a page"
1866 'nosuchrcid' => array(
1867 'code' => 'nosuchrcid',
1868 'info' => "There is no change with rcid \"\$1\""
1870 'nosuchlogid' => array(
1871 'code' => 'nosuchlogid',
1872 'info' => "There is no log entry with ID \"\$1\""
1874 'protect-invalidaction' => array(
1875 'code' => 'protect-invalidaction',
1876 'info' => "Invalid protection type \"\$1\""
1878 'protect-invalidlevel' => array(
1879 'code' => 'protect-invalidlevel',
1880 'info' => "Invalid protection level \"\$1\""
1882 'toofewexpiries' => array(
1883 'code' => 'toofewexpiries',
1884 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1886 'cantimport' => array(
1887 'code' => 'cantimport',
1888 'info' => "You don't have permission to import pages"
1890 'cantimport-upload' => array(
1891 'code' => 'cantimport-upload',
1892 'info' => "You don't have permission to import uploaded pages"
1894 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1895 'importuploaderrorsize' => array(
1896 'code' => 'filetoobig',
1897 'info' => 'The file you uploaded is bigger than the maximum upload size'
1899 'importuploaderrorpartial' => array(
1900 'code' => 'partialupload',
1901 'info' => 'The file was only partially uploaded'
1903 'importuploaderrortemp' => array(
1904 'code' => 'notempdir',
1905 'info' => 'The temporary upload directory is missing'
1907 'importcantopen' => array(
1908 'code' => 'cantopenfile',
1909 'info' => "Couldn't open the uploaded file"
1911 'import-noarticle' => array(
1912 'code' => 'badinterwiki',
1913 'info' => 'Invalid interwiki title specified'
1915 'importbadinterwiki' => array(
1916 'code' => 'badinterwiki',
1917 'info' => 'Invalid interwiki title specified'
1919 'import-unknownerror' => array(
1920 'code' => 'import-unknownerror',
1921 'info' => "Unknown error on import: \"\$1\""
1923 'cantoverwrite-sharedfile' => array(
1924 'code' => 'cantoverwrite-sharedfile',
1925 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1927 'sharedfile-exists' => array(
1928 'code' => 'fileexists-sharedrepo-perm',
1929 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1931 'mustbeposted' => array(
1932 'code' => 'mustbeposted',
1933 'info' => "The \$1 module requires a POST request"
1937 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1939 'specialpage-cantexecute' => array(
1940 'code' => 'specialpage-cantexecute',
1941 'info' => "You don't have permission to view the results of this special page"
1943 'invalidoldimage' => array(
1944 'code' => 'invalidoldimage',
1945 'info' => 'The oldimage parameter has invalid format'
1947 'nodeleteablefile' => array(
1948 'code' => 'nodeleteablefile',
1949 'info' => 'No such old version of the file'
1951 'fileexists-forbidden' => array(
1952 'code' => 'fileexists-forbidden',
1953 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1955 'fileexists-shared-forbidden' => array(
1956 'code' => 'fileexists-shared-forbidden',
1957 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1959 'filerevert-badversion' => array(
1960 'code' => 'filerevert-badversion',
1961 'info' => 'There is no previous local version of this file with the provided timestamp.'
1964 // ApiEditPage messages
1965 'noimageredirect-anon' => array(
1966 'code' => 'noimageredirect-anon',
1967 'info' => "Anonymous users can't create image redirects"
1969 'noimageredirect-logged' => array(
1970 'code' => 'noimageredirect',
1971 'info' => "You don't have permission to create image redirects"
1973 'spamdetected' => array(
1974 'code' => 'spamdetected',
1975 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1977 'contenttoobig' => array(
1978 'code' => 'contenttoobig',
1979 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1981 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1982 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1983 'wasdeleted' => array(
1984 'code' => 'pagedeleted',
1985 'info' => "The page has been deleted since you fetched its timestamp"
1987 'blankpage' => array(
1988 'code' => 'emptypage',
1989 'info' => "Creating new, empty pages is not allowed"
1991 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1992 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1993 'missingtext' => array(
1995 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1997 'emptynewsection' => array(
1998 'code' => 'emptynewsection',
1999 'info' => 'Creating empty new sections is not possible.'
2001 'revwrongpage' => array(
2002 'code' => 'revwrongpage',
2003 'info' => "r\$1 is not a revision of \"\$2\""
2005 'undo-failure' => array(
2006 'code' => 'undofailure',
2007 'info' => 'Undo failed due to conflicting intermediate edits'
2009 'content-not-allowed-here' => array(
2010 'code' => 'contentnotallowedhere',
2011 'info' => 'Content model "$1" is not allowed at title "$2"'
2014 // Messages from WikiPage::doEit()
2015 'edit-hook-aborted' => array(
2016 'code' => 'edit-hook-aborted',
2017 'info' => "Your edit was aborted by an ArticleSave hook"
2019 'edit-gone-missing' => array(
2020 'code' => 'edit-gone-missing',
2021 'info' => "The page you tried to edit doesn't seem to exist anymore"
2023 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2024 'edit-already-exists' => array(
2025 'code' => 'edit-already-exists',
2026 'info' => 'It seems the page you tried to create already exist'
2030 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
2031 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
2032 'uploaddisabled' => array(
2033 'code' => 'uploaddisabled',
2034 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2036 'copyuploaddisabled' => array(
2037 'code' => 'copyuploaddisabled',
2038 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2040 'copyuploadbaddomain' => array(
2041 'code' => 'copyuploadbaddomain',
2042 'info' => 'Uploads by URL are not allowed from this domain.'
2044 'copyuploadbadurl' => array(
2045 'code' => 'copyuploadbadurl',
2046 'info' => 'Upload not allowed from this URL.'
2049 'filename-tooshort' => array(
2050 'code' => 'filename-tooshort',
2051 'info' => 'The filename is too short'
2053 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
2054 'illegal-filename' => array(
2055 'code' => 'illegal-filename',
2056 'info' => 'The filename is not allowed'
2058 'filetype-missing' => array(
2059 'code' => 'filetype-missing',
2060 'info' => 'The file is missing an extension'
2063 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
2065 // @codingStandardsIgnoreEnd
2068 * Helper function for readonly errors
2070 * @throws UsageException always
2072 public function dieReadOnly() {
2073 $parsed = $this->parseMsg( array( 'readonlytext' ) );
2074 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2075 array( 'readonlyreason' => wfReadOnlyReason() ) );
2079 * Output the error message related to a certain array
2080 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2081 * @throws UsageException always
2083 public function dieUsageMsg( $error ) {
2084 # most of the time we send a 1 element, so we might as well send it as
2085 # a string and make this an array here.
2086 if ( is_string( $error ) ) {
2087 $error = array( $error );
2089 $parsed = $this->parseMsg( $error );
2090 $extraData = isset( $parsed['data'] ) ?
$parsed['data'] : null;
2091 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2095 * Will only set a warning instead of failing if the global $wgDebugAPI
2096 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2097 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2098 * @throws UsageException
2101 public function dieUsageMsgOrDebug( $error ) {
2102 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2103 $this->dieUsageMsg( $error );
2106 if ( is_string( $error ) ) {
2107 $error = array( $error );
2109 $parsed = $this->parseMsg( $error );
2110 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2114 * Die with the $prefix.'badcontinue' error. This call is common enough to
2115 * make it into the base method.
2116 * @param bool $condition Will only die if this value is true
2117 * @throws UsageException
2120 protected function dieContinueUsageIf( $condition ) {
2123 'Invalid continue param. You should pass the original value returned by the previous query',
2129 * Return the error message related to a certain array
2130 * @param array $error Element of a getUserPermissionsErrors()-style array
2131 * @return array('code' => code, 'info' => info)
2133 public function parseMsg( $error ) {
2134 $error = (array)$error; // It seems strings sometimes make their way in here
2135 $key = array_shift( $error );
2137 // Check whether the error array was nested
2138 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2139 if ( is_array( $key ) ) {
2141 $key = array_shift( $error );
2144 if ( $key instanceof IApiMessage
) {
2146 'code' => $key->getApiCode(),
2147 'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2148 'data' => $key->getApiData()
2152 if ( isset( self
::$messageMap[$key] ) ) {
2154 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
2155 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2159 // If the key isn't present, throw an "unknown error"
2160 return $this->parseMsg( array( 'unknownerror', $key ) );
2164 * Internal code errors should be reported with this method
2165 * @param string $method Method or function name
2166 * @param string $message Error message
2167 * @throws MWException always
2169 protected static function dieDebug( $method, $message ) {
2170 throw new MWException( "Internal error in $method: $message" );
2174 * Write logging information for API features to a debug log, for usage
2176 * @param string $feature Feature being used.
2178 protected function logFeatureUsage( $feature ) {
2179 $request = $this->getRequest();
2180 $s = '"' . addslashes( $feature ) . '"' .
2181 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2182 ' "' . $request->getIP() . '"' .
2183 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2184 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2185 wfDebugLog( 'api-feature-usage', $s, 'private' );
2190 /************************************************************************//**
2191 * @name Help message generation
2196 * Return the description message.
2198 * @return string|array|Message
2200 protected function getDescriptionMessage() {
2201 return "apihelp-{$this->getModulePath()}-description";
2205 * Get final module description, after hooks have had a chance to tweak it as
2208 * @since 1.25, returns Message[] rather than string[]
2211 public function getFinalDescription() {
2212 $desc = $this->getDescription();
2213 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2214 $desc = self
::escapeWikiText( $desc );
2215 if ( is_array( $desc ) ) {
2216 $desc = join( "\n", $desc );
2218 $desc = (string)$desc;
2221 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2222 $this->getModulePrefix(),
2223 $this->getModuleName(),
2224 $this->getModulePath(),
2226 if ( !$msg->exists() ) {
2227 $msg = $this->msg( 'api-help-fallback-description', $desc );
2229 $msgs = array( $msg );
2231 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2237 * Get final list of parameters, after hooks have had a chance to
2238 * tweak it as needed.
2240 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2241 * @return array|bool False on no parameters
2242 * @since 1.21 $flags param added
2244 public function getFinalParams( $flags = 0 ) {
2245 $params = $this->getAllowedParams( $flags );
2250 if ( $this->needsToken() ) {
2251 $params['token'] = array(
2252 ApiBase
::PARAM_TYPE
=> 'string',
2253 ApiBase
::PARAM_REQUIRED
=> true,
2254 ApiBase
::PARAM_HELP_MSG
=> array(
2255 'api-help-param-token',
2256 $this->needsToken(),
2258 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2261 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2267 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2270 * @since 1.25, returns array of Message[] rather than array of string[]
2271 * @return array Keys are parameter names, values are arrays of Message objects
2273 public function getFinalParamDescription() {
2274 $prefix = $this->getModulePrefix();
2275 $name = $this->getModuleName();
2276 $path = $this->getModulePath();
2278 $desc = $this->getParamDescription();
2279 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2284 $desc = self
::escapeWikiText( $desc );
2286 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2288 foreach ( $params as $param => $settings ) {
2289 if ( !is_array( $settings ) ) {
2290 $settings = array();
2293 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2294 if ( is_array( $d ) ) {
2295 // Special handling for prop parameters
2296 $d = array_map( function ( $line ) {
2297 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2298 $line = "\n;{$m[1]}:{$m[2]}";
2302 $d = join( ' ', $d );
2305 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2306 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2308 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2309 if ( !$msg->exists() ) {
2310 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2313 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2314 array( $prefix, $param, $name, $path ) );
2316 $this->dieDebug( __METHOD__
,
2317 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2319 $msgs[$param] = array( $msg );
2321 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2322 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2323 $this->dieDebug( __METHOD__
,
2324 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2326 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2327 $this->dieDebug( __METHOD__
,
2328 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2329 'ApiBase::PARAM_TYPE is an array' );
2332 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2333 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2334 if ( isset( $valueMsgs[$value] ) ) {
2335 $msg = $valueMsgs[$value];
2337 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2339 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2340 array( $prefix, $param, $name, $path, $value ) );
2342 $m = new ApiHelpParamValueMessage(
2344 array( $m->getKey(), 'api-help-param-no-description' ),
2347 $msgs[$param][] = $m->setContext( $this->getContext() );
2349 $this->dieDebug( __METHOD__
,
2350 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2355 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2356 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2357 $this->dieDebug( __METHOD__
,
2358 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2360 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2361 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2362 array( $prefix, $param, $name, $path ) );
2364 $msgs[$param][] = $m;
2366 $this->dieDebug( __METHOD__
,
2367 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2373 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2379 * Generates the list of flags for the help screen and for action=paraminfo
2381 * Corresponding messages: api-help-flag-deprecated,
2382 * api-help-flag-internal, api-help-flag-readrights,
2383 * api-help-flag-writerights, api-help-flag-mustbeposted
2387 protected function getHelpFlags() {
2390 if ( $this->isDeprecated() ) {
2391 $flags[] = 'deprecated';
2393 if ( $this->isInternal() ) {
2394 $flags[] = 'internal';
2396 if ( $this->isReadMode() ) {
2397 $flags[] = 'readrights';
2399 if ( $this->isWriteMode() ) {
2400 $flags[] = 'writerights';
2402 if ( $this->mustBePosted() ) {
2403 $flags[] = 'mustbeposted';
2410 * Returns information about the source of this module, if known
2412 * Returned array is an array with the following keys:
2413 * - path: Install path
2414 * - name: Extension name, or "MediaWiki" for core
2415 * - namemsg: (optional) i18n message key for a display name
2416 * - license-name: (optional) Name of license
2418 * @return array|null
2420 protected function getModuleSourceInfo() {
2423 if ( $this->mModuleSource
!== false ) {
2424 return $this->mModuleSource
;
2427 // First, try to find where the module comes from...
2428 $rClass = new ReflectionClass( $this );
2429 $path = $rClass->getFileName();
2432 $this->mModuleSource
= null;
2435 $path = realpath( $path ) ?
: $path;
2437 // Build map of extension directories to extension info
2438 if ( self
::$extensionInfo === null ) {
2439 self
::$extensionInfo = array(
2440 realpath( __DIR__
) ?
: __DIR__
=> array(
2442 'name' => 'MediaWiki',
2443 'license-name' => 'GPL-2.0+',
2445 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2451 'license-name' => null,
2453 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2454 foreach ( $group as $ext ) {
2455 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2456 // This shouldn't happen, but does anyway.
2460 $extpath = $ext['path'];
2461 if ( !is_dir( $extpath ) ) {
2462 $extpath = dirname( $extpath );
2464 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2465 array_intersect_key( $ext, $keep );
2468 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2469 $extpath = $ext['path'];
2470 if ( !is_dir( $extpath ) ) {
2471 $extpath = dirname( $extpath );
2473 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2474 array_intersect_key( $ext, $keep );
2478 // Now traverse parent directories until we find a match or run out of
2481 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2483 $this->mModuleSource
= self
::$extensionInfo[$path];
2484 return $this->mModuleSource
;
2488 $path = dirname( $path );
2489 } while ( $path !== $oldpath );
2491 // No idea what extension this might be.
2492 $this->mModuleSource
= null;
2497 * Called from ApiHelp before the pieces are joined together and returned.
2499 * This exists mainly for ApiMain to add the Permissions and Credits
2500 * sections. Other modules probably don't need it.
2502 * @param string[] &$help Array of help data
2503 * @param array $options Options passed to ApiHelp::getHelp
2504 * @param array &$tocData If a TOC is being generated, this array has keys
2505 * as anchors in the page and values as for Linker::generateTOC().
2507 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2512 /************************************************************************//**
2517 /// @deprecated since 1.24
2518 const PROP_ROOT
= 'ROOT';
2519 /// @deprecated since 1.24
2520 const PROP_LIST
= 'LIST';
2521 /// @deprecated since 1.24
2522 const PROP_TYPE
= 0;
2523 /// @deprecated since 1.24
2524 const PROP_NULLABLE
= 1;
2527 * Formerly returned a string that identifies the version of the extending
2528 * class. Typically included the class name, the svn revision, timestamp,
2529 * and last author. Usually done with SVN's Id keyword
2531 * @deprecated since 1.21, version string is no longer supported
2534 public function getVersion() {
2535 wfDeprecated( __METHOD__
, '1.21' );
2540 * Formerly used to fetch a list of possible properites in the result,
2541 * somehow organized with respect to the prop parameter that causes them to
2542 * be returned. The specific semantics of the return value was never
2543 * specified. Since this was never possible to be accurately updated, it
2546 * @deprecated since 1.24
2547 * @return array|bool
2549 protected function getResultProperties() {
2550 wfDeprecated( __METHOD__
, '1.24' );
2555 * @see self::getResultProperties()
2556 * @deprecated since 1.24
2557 * @return array|bool
2559 public function getFinalResultProperties() {
2560 wfDeprecated( __METHOD__
, '1.24' );
2565 * @see self::getResultProperties()
2566 * @deprecated since 1.24
2568 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2569 wfDeprecated( __METHOD__
, '1.24' );
2573 * @see self::getPossibleErrors()
2574 * @deprecated since 1.24
2577 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2578 wfDeprecated( __METHOD__
, '1.24' );
2583 * @see self::getPossibleErrors()
2584 * @deprecated since 1.24
2587 public function getRequireMaxOneParameterErrorMessages( $params ) {
2588 wfDeprecated( __METHOD__
, '1.24' );
2593 * @see self::getPossibleErrors()
2594 * @deprecated since 1.24
2597 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2598 wfDeprecated( __METHOD__
, '1.24' );
2603 * @see self::getPossibleErrors()
2604 * @deprecated since 1.24
2607 public function getTitleOrPageIdErrorMessage() {
2608 wfDeprecated( __METHOD__
, '1.24' );
2613 * This formerly attempted to return a list of all possible errors returned
2614 * by the module. However, this was impossible to maintain in many cases
2615 * since errors could come from other areas of MediaWiki and in some cases
2616 * from arbitrary extension hooks. Since a partial list claiming to be
2617 * comprehensive is unlikely to be useful, it was removed.
2619 * @deprecated since 1.24
2622 public function getPossibleErrors() {
2623 wfDeprecated( __METHOD__
, '1.24' );
2628 * @see self::getPossibleErrors()
2629 * @deprecated since 1.24
2632 public function getFinalPossibleErrors() {
2633 wfDeprecated( __METHOD__
, '1.24' );
2638 * @see self::getPossibleErrors()
2639 * @deprecated since 1.24
2642 public function parseErrors( $errors ) {
2643 wfDeprecated( __METHOD__
, '1.24' );
2648 * Returns the description string for this module
2650 * Ignored if an i18n message exists for
2651 * "apihelp-{$this->getModulePath()}-description".
2653 * @deprecated since 1.25
2654 * @return Message|string|array
2656 protected function getDescription() {
2661 * Returns an array of parameter descriptions.
2663 * For each parameter, ignored if an i18n message exists for the parameter.
2664 * By default that message is
2665 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2666 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2667 * self::getFinalParams().
2669 * @deprecated since 1.25
2670 * @return array|bool False on no parameter descriptions
2672 protected function getParamDescription() {
2677 * Returns usage examples for this module.
2679 * Return value as an array is either:
2680 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2682 * - sequential numeric keys with even-numbered keys being display-text
2683 * and odd-numbered keys being partial urls
2684 * - partial URLs as keys with display-text (string or array-to-be-joined)
2686 * Return value as a string is the same as an array with a numeric key and
2687 * that value, and boolean false means "no examples".
2689 * @deprecated since 1.25, use getExamplesMessages() instead
2690 * @return bool|string|array
2692 protected function getExamples() {
2697 * Generates help message for this module, or false if there is no description
2698 * @deprecated since 1.25
2699 * @return string|bool
2701 public function makeHelpMsg() {
2702 wfDeprecated( __METHOD__
, '1.25' );
2703 static $lnPrfx = "\n ";
2705 $msg = $this->getFinalDescription();
2707 if ( $msg !== false ) {
2709 if ( !is_array( $msg ) ) {
2714 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2716 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2718 if ( $this->isReadMode() ) {
2719 $msg .= "\nThis module requires read rights";
2721 if ( $this->isWriteMode() ) {
2722 $msg .= "\nThis module requires write rights";
2724 if ( $this->mustBePosted() ) {
2725 $msg .= "\nThis module only accepts POST requests";
2727 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2728 $this->mustBePosted()
2734 $paramsMsg = $this->makeHelpMsgParameters();
2735 if ( $paramsMsg !== false ) {
2736 $msg .= "Parameters:\n$paramsMsg";
2739 $examples = $this->getExamples();
2741 if ( !is_array( $examples ) ) {
2746 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2747 foreach ( $examples as $k => $v ) {
2748 if ( is_numeric( $k ) ) {
2751 if ( is_array( $v ) ) {
2752 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2754 $msgExample = " $v";
2757 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2767 * @deprecated since 1.25
2768 * @param string $item
2771 private function indentExampleText( $item ) {
2776 * @deprecated since 1.25
2777 * @param string $prefix Text to split output items
2778 * @param string $title What is being output
2779 * @param string|array $input
2782 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2783 wfDeprecated( __METHOD__
, '1.25' );
2784 if ( $input === false ) {
2787 if ( !is_array( $input ) ) {
2788 $input = array( $input );
2791 if ( count( $input ) > 0 ) {
2793 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2797 $msg .= implode( $prefix, $input ) . "\n";
2806 * Generates the parameter descriptions for this module, to be displayed in the
2808 * @deprecated since 1.25
2809 * @return string|bool
2811 public function makeHelpMsgParameters() {
2812 wfDeprecated( __METHOD__
, '1.25' );
2813 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2815 $paramsDescription = $this->getFinalParamDescription();
2817 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2818 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2819 foreach ( $params as $paramName => $paramSettings ) {
2820 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2821 if ( is_array( $desc ) ) {
2822 $desc = implode( $paramPrefix, $desc );
2826 if ( !is_array( $paramSettings ) ) {
2827 $paramSettings = array(
2828 self
::PARAM_DFLT
=> $paramSettings,
2832 // handle missing type
2833 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2834 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2835 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2837 if ( is_bool( $dflt ) ) {
2838 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2839 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2840 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2841 } elseif ( is_int( $dflt ) ) {
2842 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2846 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2847 && $paramSettings[self
::PARAM_DEPRECATED
]
2849 $desc = "DEPRECATED! $desc";
2852 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2853 && $paramSettings[self
::PARAM_REQUIRED
]
2855 $desc .= $paramPrefix . "This parameter is required";
2858 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2859 ?
$paramSettings[self
::PARAM_TYPE
]
2861 if ( isset( $type ) ) {
2862 $hintPipeSeparated = true;
2863 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2864 ?
$paramSettings[self
::PARAM_ISMULTI
]
2867 $prompt = 'Values (separate with \'|\'): ';
2869 $prompt = 'One value: ';
2872 if ( $type === 'submodule' ) {
2873 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2874 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2876 $type = $this->getModuleManager()->getNames( $paramName );
2880 if ( is_array( $type ) ) {
2882 $nothingPrompt = '';
2883 foreach ( $type as $t ) {
2885 $nothingPrompt = 'Can be empty, or ';
2890 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2891 $choicesstring = implode( ', ', $choices );
2892 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2893 $hintPipeSeparated = false;
2897 // Special handling because namespaces are
2898 // type-limited, yet they are not given
2899 $desc .= $paramPrefix . $prompt;
2900 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2901 100, $descWordwrap );
2902 $hintPipeSeparated = false;
2905 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2906 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2907 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2909 $desc .= ' allowed';
2912 $s = $multi ?
's' : '';
2913 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2914 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2915 if ( $hasMin ||
$hasMax ) {
2917 $intRangeStr = "The value$s must be no less than " .
2918 "{$paramSettings[self::PARAM_MIN]}";
2919 } elseif ( !$hasMin ) {
2920 $intRangeStr = "The value$s must be no more than " .
2921 "{$paramSettings[self::PARAM_MAX]}";
2923 $intRangeStr = "The value$s must be between " .
2924 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2927 $desc .= $paramPrefix . $intRangeStr;
2931 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2937 if ( $hintPipeSeparated ) {
2938 $desc .= $paramPrefix . "Separate values with '|'";
2941 $isArray = is_array( $type );
2943 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2945 $desc .= $paramPrefix . "Maximum number of values " .
2946 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2951 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2952 if ( !is_null( $default ) && $default !== false ) {
2953 $desc .= $paramPrefix . "Default: $default";
2956 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2966 * @deprecated since 1.25, always returns empty string
2967 * @param IDatabase|bool $db
2970 public function getModuleProfileName( $db = false ) {
2971 wfDeprecated( __METHOD__
, '1.25' );
2976 * @deprecated since 1.25
2978 public function profileIn() {
2979 // No wfDeprecated() yet because extensions call this and might need to
2980 // keep doing so for BC.
2984 * @deprecated since 1.25
2986 public function profileOut() {
2987 // No wfDeprecated() yet because extensions call this and might need to
2988 // keep doing so for BC.
2992 * @deprecated since 1.25
2994 public function safeProfileOut() {
2995 wfDeprecated( __METHOD__
, '1.25' );
2999 * @deprecated since 1.25, always returns 0
3002 public function getProfileTime() {
3003 wfDeprecated( __METHOD__
, '1.25' );
3008 * @deprecated since 1.25
3010 public function profileDBIn() {
3011 wfDeprecated( __METHOD__
, '1.25' );
3015 * @deprecated since 1.25
3017 public function profileDBOut() {
3018 wfDeprecated( __METHOD__
, '1.25' );
3022 * @deprecated since 1.25, always returns 0
3025 public function getProfileDBTime() {
3026 wfDeprecated( __METHOD__
, '1.25' );
3031 * Get the result data array (read-only)
3032 * @deprecated since 1.25, use $this->getResult() methods instead
3035 public function getResultData() {
3036 wfDeprecated( __METHOD__
, '1.25' );
3037 return $this->getResult()->getData();
3041 * Call wfTransactionalTimeLimit() if this request was POSTed
3044 protected function useTransactionalTimeLimit() {
3045 if ( $this->getRequest()->wasPosted() ) {
3046 wfTransactionalTimeLimit();
3054 * For really cool vim folding this needs to be at the end:
3055 * vim: foldmarker=@{,@} foldmethod=marker