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 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Specify an alternative i18n message for this help parameter.
69 // Value is $msg for ApiBase::makeMessage()
70 const PARAM_HELP_MSG
= 10;
72 // Specify additional i18n messages to append to the normal message. Value
73 // is an array of $msg for ApiBase::makeMessage()
74 const PARAM_HELP_MSG_APPEND
= 11;
76 // Specify additional information tags for the parameter. Value is an array
77 // of arrays, with the first member being the 'tag' for the info and the
78 // remaining members being the values. In the help, this is formatted using
79 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
80 // comma-joined list of values, $3 = module prefix.
81 const PARAM_HELP_MSG_INFO
= 12;
83 // When PARAM_TYPE is an array, this may be an array mapping those values
84 // to page titles which will be linked in the help.
85 const PARAM_VALUE_LINKS
= 13;
87 // When PARAM_TYPE is an array, this is an array mapping those values to
88 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
89 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
90 const PARAM_HELP_MSG_PER_VALUE
= 14;
92 const LIMIT_BIG1
= 500; // Fast query, std user limit
93 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
94 const LIMIT_SML1
= 50; // Slow query, std user limit
95 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
98 * getAllowedParams() flag: When set, the result could take longer to generate,
99 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
102 const GET_VALUES_FOR_HELP
= 1;
105 private $mMainModule;
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
112 * @param ApiMain $mainModule
113 * @param string $moduleName Name of this module
114 * @param string $modulePrefix Prefix to use for parameter names
116 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
117 $this->mMainModule
= $mainModule;
118 $this->mModuleName
= $moduleName;
119 $this->mModulePrefix
= $modulePrefix;
121 if ( !$this->isMain() ) {
122 $this->setContext( $mainModule->getContext() );
127 /************************************************************************//**
128 * @name Methods to implement
133 * Evaluates the parameters, performs the requested query, and sets up
134 * the result. Concrete implementations of ApiBase must override this
135 * method to provide whatever functionality their module offers.
136 * Implementations must not produce any output on their own and are not
137 * expected to handle any errors.
139 * The execute() method will be invoked directly by ApiMain immediately
140 * before the result of the module is output. Aside from the
141 * constructor, implementations should assume that no other methods
142 * will be called externally on the module before the result is
145 * The result data should be stored in the ApiResult object available
146 * through getResult().
148 abstract public function execute();
151 * Get the module manager, or null if this module has no sub-modules
153 * @return ApiModuleManager
155 public function getModuleManager() {
160 * If the module may only be used with a certain format module,
161 * it should override this method to return an instance of that formatter.
162 * A value of null means the default format will be used.
163 * @return mixed Instance of a derived class of ApiFormatBase, or null
165 public function getCustomPrinter() {
170 * Returns usage examples for this module.
172 * Return value has query strings as keys, with values being either strings
173 * (message key), arrays (message key + parameter), or Message objects.
175 * Do not call this base class implementation when overriding this method.
180 protected function getExamplesMessages() {
181 // Fall back to old non-localised method
184 $examples = $this->getExamples();
186 if ( !is_array( $examples ) ) {
187 $examples = array( $examples );
188 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
189 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
190 !preg_match( '/^\s*api\.php\?/', $examples[0] )
192 // Fix up the ugly "even numbered elements are description, odd
193 // numbered elemts are the link" format (see doc for self::getExamples)
195 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
196 $tmp[$examples[$i +
1]] = $examples[$i];
201 foreach ( $examples as $k => $v ) {
202 if ( is_numeric( $k ) ) {
207 $msg = self
::escapeWikiText( $v );
208 if ( is_array( $msg ) ) {
209 $msg = join( " ", $msg );
213 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
214 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
222 * Return links to more detailed help pages about the module.
223 * @since 1.25, returning boolean false is deprecated
224 * @return string|array
226 public function getHelpUrls() {
231 * Returns an array of allowed parameters (parameter name) => (default
232 * value) or (parameter name) => (array with PARAM_* constants as keys)
233 * Don't call this function directly: use getFinalParams() to allow
234 * hooks to modify parameters as needed.
236 * Some derived classes may choose to handle an integer $flags parameter
237 * in the overriding methods. Callers of this method can pass zero or
238 * more OR-ed flags like GET_VALUES_FOR_HELP.
242 protected function getAllowedParams( /* $flags = 0 */ ) {
243 // int $flags is not declared because it causes "Strict standards"
244 // warning. Most derived classes do not implement it.
249 * Indicates if this module needs maxlag to be checked
252 public function shouldCheckMaxlag() {
257 * Indicates whether this module requires read rights
260 public function isReadMode() {
265 * Indicates whether this module requires write mode
268 public function isWriteMode() {
273 * Indicates whether this module must be called with a POST request
276 public function mustBePosted() {
277 return $this->needsToken() !== false;
281 * Indicates whether this module is deprecated
285 public function isDeprecated() {
290 * Indicates whether this module is "internal"
291 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
295 public function isInternal() {
300 * Returns the token type this module requires in order to execute.
302 * Modules are strongly encouraged to use the core 'csrf' type unless they
303 * have specialized security needs. If the token type is not one of the
304 * core types, you must use the ApiQueryTokensRegisterTypes hook to
307 * Returning a non-falsey value here will force the addition of an
308 * appropriate 'token' parameter in self::getFinalParams(). Also,
309 * self::mustBePosted() must return true when tokens are used.
311 * In previous versions of MediaWiki, true was a valid return value.
312 * Returning true will generate errors indicating that the API module needs
315 * @return string|false
317 public function needsToken() {
322 * Fetch the salt used in the Web UI corresponding to this module.
324 * Only override this if the Web UI uses a token with a non-constant salt.
327 * @param array $params All supplied parameters for the module
328 * @return string|array|null
330 protected function getWebUITokenSalt( array $params ) {
336 /************************************************************************//**
337 * @name Data access methods
342 * Get the name of the module being executed by this instance
345 public function getModuleName() {
346 return $this->mModuleName
;
350 * Get parameter prefix (usually two letters or an empty string).
353 public function getModulePrefix() {
354 return $this->mModulePrefix
;
358 * Get the main module
361 public function getMain() {
362 return $this->mMainModule
;
366 * Returns true if this module is the main module ($this === $this->mMainModule),
370 public function isMain() {
371 return $this === $this->mMainModule
;
375 * Get the parent of this module
377 * @return ApiBase|null
379 public function getParent() {
380 return $this->isMain() ?
null : $this->getMain();
384 * Returns true if the current request breaks the same-origin policy.
386 * For example, json with callbacks.
388 * https://en.wikipedia.org/wiki/Same-origin_policy
393 public function lacksSameOriginSecurity() {
394 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
398 * Get the path to this module
403 public function getModulePath() {
404 if ( $this->isMain() ) {
406 } elseif ( $this->getParent()->isMain() ) {
407 return $this->getModuleName();
409 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
414 * Get a module from its module path
417 * @param string $path
418 * @return ApiBase|null
419 * @throws UsageException
421 public function getModuleFromPath( $path ) {
422 $module = $this->getMain();
423 if ( $path === 'main' ) {
427 $parts = explode( '+', $path );
428 if ( count( $parts ) === 1 ) {
429 // In case the '+' was typed into URL, it resolves as a space
430 $parts = explode( ' ', $path );
433 $count = count( $parts );
434 for ( $i = 0; $i < $count; $i++
) {
436 $manager = $parent->getModuleManager();
437 if ( $manager === null ) {
438 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
439 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
441 $module = $manager->getModule( $parts[$i] );
443 if ( $module === null ) {
444 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
446 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
456 * Get the result object
459 public function getResult() {
460 // Main module has getResult() method overridden
461 // Safety - avoid infinite loop:
462 if ( $this->isMain() ) {
463 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
466 return $this->getMain()->getResult();
470 * Get the result data array (read-only)
473 public function getResultData() {
474 return $this->getResult()->getData();
478 * Gets a default slave database connection object
479 * @return DatabaseBase
481 protected function getDB() {
482 if ( !isset( $this->mSlaveDB
) ) {
483 $this->profileDBIn();
484 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
485 $this->profileDBOut();
488 return $this->mSlaveDB
;
493 /************************************************************************//**
494 * @name Parameter handling
499 * This method mangles parameter name based on the prefix supplied to the constructor.
500 * Override this method to change parameter name during runtime
501 * @param string $paramName Parameter name
502 * @return string Prefixed parameter name
504 public function encodeParamName( $paramName ) {
505 return $this->mModulePrefix
. $paramName;
509 * Using getAllowedParams(), this function makes an array of the values
510 * provided by the user, with key being the name of the variable, and
511 * value - validated value from user or default. limits will not be
512 * parsed if $parseLimit is set to false; use this when the max
513 * limit is not definitive yet, e.g. when getting revisions.
514 * @param bool $parseLimit True by default
517 public function extractRequestParams( $parseLimit = true ) {
518 // Cache parameters, for performance and to avoid bug 24564.
519 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
520 $params = $this->getFinalParams();
523 if ( $params ) { // getFinalParams() can return false
524 foreach ( $params as $paramName => $paramSettings ) {
525 $results[$paramName] = $this->getParameterFromSettings(
526 $paramName, $paramSettings, $parseLimit );
529 $this->mParamCache
[$parseLimit] = $results;
532 return $this->mParamCache
[$parseLimit];
536 * Get a value for the given parameter
537 * @param string $paramName Parameter name
538 * @param bool $parseLimit See extractRequestParams()
539 * @return mixed Parameter value
541 protected function getParameter( $paramName, $parseLimit = true ) {
542 $params = $this->getFinalParams();
543 $paramSettings = $params[$paramName];
545 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
549 * Die if none or more than one of a certain set of parameters is set and not false.
551 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
552 * @param string $required,... Names of parameters of which exactly one must be set
554 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
555 $required = func_get_args();
556 array_shift( $required );
557 $p = $this->getModulePrefix();
559 $intersection = array_intersect( array_keys( array_filter( $params,
560 array( $this, "parameterNotEmpty" ) ) ), $required );
562 if ( count( $intersection ) > 1 ) {
564 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
566 } elseif ( count( $intersection ) == 0 ) {
568 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
575 * Die if more than one of a certain set of parameters is set and not false.
577 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
578 * @param string $required,... Names of parameters of which at most one must be set
580 public function requireMaxOneParameter( $params, $required /*...*/ ) {
581 $required = func_get_args();
582 array_shift( $required );
583 $p = $this->getModulePrefix();
585 $intersection = array_intersect( array_keys( array_filter( $params,
586 array( $this, "parameterNotEmpty" ) ) ), $required );
588 if ( count( $intersection ) > 1 ) {
590 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
597 * Die if none of a certain set of parameters is set and not false.
600 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
601 * @param string $required,... Names of parameters of which at least one must be set
603 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
604 $required = func_get_args();
605 array_shift( $required );
606 $p = $this->getModulePrefix();
608 $intersection = array_intersect(
609 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
613 if ( count( $intersection ) == 0 ) {
614 $this->dieUsage( "At least one of the parameters {$p}" .
615 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
620 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
622 * @param object $x Parameter to check is not null/false
625 private function parameterNotEmpty( $x ) {
626 return !is_null( $x ) && $x !== false;
630 * Get a WikiPage object from a title or pageid param, if possible.
631 * Can die, if no param is set or if the title or page id is not valid.
633 * @param array $params
634 * @param bool|string $load Whether load the object's state from the database:
635 * - false: don't load (if the pageid is given, it will still be loaded)
636 * - 'fromdb': load from a slave database
637 * - 'fromdbmaster': load from the master database
640 public function getTitleOrPageId( $params, $load = false ) {
641 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
644 if ( isset( $params['title'] ) ) {
645 $titleObj = Title
::newFromText( $params['title'] );
646 if ( !$titleObj ||
$titleObj->isExternal() ) {
647 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
649 if ( !$titleObj->canExist() ) {
650 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
652 $pageObj = WikiPage
::factory( $titleObj );
653 if ( $load !== false ) {
654 $pageObj->loadPageData( $load );
656 } elseif ( isset( $params['pageid'] ) ) {
657 if ( $load === false ) {
660 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
662 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
670 * Return true if we're to watch the page, false if not, null if no change.
671 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
672 * @param Title $titleObj The page under consideration
673 * @param string $userOption The user option to consider when $watchlist=preferences.
674 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
677 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
679 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
681 switch ( $watchlist ) {
689 # If the user is already watching, don't bother checking
690 if ( $userWatching ) {
693 # If no user option was passed, use watchdefault and watchcreations
694 if ( is_null( $userOption ) ) {
695 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
696 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
699 # Watch the article based on the user preference
700 return $this->getUser()->getBoolOption( $userOption );
703 return $userWatching;
706 return $userWatching;
711 * Using the settings determine the value for the given parameter
713 * @param string $paramName Parameter name
714 * @param array|mixed $paramSettings Default value or an array of settings
715 * using PARAM_* constants.
716 * @param bool $parseLimit Parse limit?
717 * @return mixed Parameter value
719 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
720 // Some classes may decide to change parameter names
721 $encParamName = $this->encodeParamName( $paramName );
723 if ( !is_array( $paramSettings ) ) {
724 $default = $paramSettings;
726 $type = gettype( $paramSettings );
731 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
732 ?
$paramSettings[self
::PARAM_DFLT
]
734 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
735 ?
$paramSettings[self
::PARAM_ISMULTI
]
737 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
738 ?
$paramSettings[self
::PARAM_TYPE
]
740 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
741 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
743 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
744 ?
$paramSettings[self
::PARAM_DEPRECATED
]
746 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
747 ?
$paramSettings[self
::PARAM_REQUIRED
]
750 // When type is not given, and no choices, the type is the same as $default
751 if ( !isset( $type ) ) {
752 if ( isset( $default ) ) {
753 $type = gettype( $default );
755 $type = 'NULL'; // allow everything
760 if ( $type == 'boolean' ) {
761 if ( isset( $default ) && $default !== false ) {
762 // Having a default value of anything other than 'false' is not allowed
765 "Boolean param $encParamName's default is set to '$default'. " .
766 "Boolean parameters must default to false."
770 $value = $this->getMain()->getCheck( $encParamName );
771 } elseif ( $type == 'upload' ) {
772 if ( isset( $default ) ) {
773 // Having a default value is not allowed
776 "File upload param $encParamName's default is set to " .
777 "'$default'. File upload parameters may not have a default." );
780 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
782 $value = $this->getMain()->getUpload( $encParamName );
783 if ( !$value->exists() ) {
784 // This will get the value without trying to normalize it
785 // (because trying to normalize a large binary file
786 // accidentally uploaded as a field fails spectacularly)
787 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
788 if ( $value !== null ) {
790 "File upload param $encParamName is not a file upload; " .
791 "be sure to use multipart/form-data for your POST and include " .
792 "a filename in the Content-Disposition header.",
793 "badupload_{$encParamName}"
798 $value = $this->getMain()->getVal( $encParamName, $default );
800 if ( isset( $value ) && $type == 'namespace' ) {
801 $type = MWNamespace
::getValidNamespaces();
803 if ( isset( $value ) && $type == 'submodule' ) {
804 $type = $this->getModuleManager()->getNames( $paramName );
808 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
809 $value = $this->parseMultiValue(
813 is_array( $type ) ?
$type : null
817 // More validation only when choices were not given
818 // choices were validated in parseMultiValue()
819 if ( isset( $value ) ) {
820 if ( !is_array( $type ) ) {
822 case 'NULL': // nothing to do
825 if ( $required && $value === '' ) {
826 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
829 case 'integer': // Force everything using intval() and optionally validate limits
830 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
831 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
832 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
833 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
835 if ( is_array( $value ) ) {
836 $value = array_map( 'intval', $value );
837 if ( !is_null( $min ) ||
!is_null( $max ) ) {
838 foreach ( $value as &$v ) {
839 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
843 $value = intval( $value );
844 if ( !is_null( $min ) ||
!is_null( $max ) ) {
845 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
850 if ( !$parseLimit ) {
851 // Don't do any validation whatsoever
854 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
855 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
859 "MAX1 or MAX2 are not defined for the limit $encParamName"
863 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
865 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
866 if ( $value == 'max' ) {
867 $value = $this->getMain()->canApiHighLimits()
868 ?
$paramSettings[self
::PARAM_MAX2
]
869 : $paramSettings[self
::PARAM_MAX
];
870 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
872 $value = intval( $value );
873 $this->validateLimit(
877 $paramSettings[self
::PARAM_MAX
],
878 $paramSettings[self
::PARAM_MAX2
]
884 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
888 if ( is_array( $value ) ) {
889 foreach ( $value as $key => $val ) {
890 $value[$key] = $this->validateTimestamp( $val, $encParamName );
893 $value = $this->validateTimestamp( $value, $encParamName );
897 if ( is_array( $value ) ) {
898 foreach ( $value as $key => $val ) {
899 $value[$key] = $this->validateUser( $val, $encParamName );
902 $value = $this->validateUser( $value, $encParamName );
905 case 'upload': // nothing to do
908 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
912 // Throw out duplicates if requested
913 if ( !$dupes && is_array( $value ) ) {
914 $value = array_unique( $value );
917 // Set a warning if a deprecated parameter has been passed
918 if ( $deprecated && $value !== false ) {
919 $this->setWarning( "The $encParamName parameter has been deprecated." );
921 } elseif ( $required ) {
922 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
929 * Return an array of values that were given in a 'a|b|c' notation,
930 * after it optionally validates them against the list allowed values.
932 * @param string $valueName The name of the parameter (for error
934 * @param mixed $value The value being parsed
935 * @param bool $allowMultiple Can $value contain more than one value
937 * @param string[]|null $allowedValues An array of values to check against. If
938 * null, all values are accepted.
939 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
941 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
942 if ( trim( $value ) === '' && $allowMultiple ) {
946 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
947 // because it unstubs $wgUser
948 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
949 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
953 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
954 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
955 "the limit is $sizeLimit" );
958 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
959 // Bug 33482 - Allow entries with | in them for non-multiple values
960 if ( in_array( $value, $allowedValues, true ) ) {
964 $possibleValues = is_array( $allowedValues )
965 ?
"of '" . implode( "', '", $allowedValues ) . "'"
968 "Only one $possibleValues is allowed for parameter '$valueName'",
969 "multival_$valueName"
973 if ( is_array( $allowedValues ) ) {
974 // Check for unknown values
975 $unknown = array_diff( $valuesList, $allowedValues );
976 if ( count( $unknown ) ) {
977 if ( $allowMultiple ) {
978 $s = count( $unknown ) > 1 ?
's' : '';
979 $vals = implode( ", ", $unknown );
980 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
983 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
988 // Now throw them out
989 $valuesList = array_intersect( $valuesList, $allowedValues );
992 return $allowMultiple ?
$valuesList : $valuesList[0];
996 * Validate the value against the minimum and user/bot maximum limits.
997 * Prints usage info on failure.
998 * @param string $paramName Parameter name
999 * @param int $value Parameter value
1000 * @param int|null $min Minimum value
1001 * @param int|null $max Maximum value for users
1002 * @param int $botMax Maximum value for sysops/bots
1003 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1005 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1006 if ( !is_null( $min ) && $value < $min ) {
1008 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1009 $this->warnOrDie( $msg, $enforceLimits );
1013 // Minimum is always validated, whereas maximum is checked only if not
1014 // running in internal call mode
1015 if ( $this->getMain()->isInternalMode() ) {
1019 // Optimization: do not check user's bot status unless really needed -- skips db query
1020 // assumes $botMax >= $max
1021 if ( !is_null( $max ) && $value > $max ) {
1022 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1023 if ( $value > $botMax ) {
1024 $msg = $this->encodeParamName( $paramName ) .
1025 " may not be over $botMax (set to $value) for bots or sysops";
1026 $this->warnOrDie( $msg, $enforceLimits );
1030 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1031 $this->warnOrDie( $msg, $enforceLimits );
1038 * Validate and normalize of parameters of type 'timestamp'
1039 * @param string $value Parameter value
1040 * @param string $encParamName Parameter name
1041 * @return string Validated and normalized parameter
1043 protected function validateTimestamp( $value, $encParamName ) {
1044 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1045 if ( $unixTimestamp === false ) {
1047 "Invalid value '$value' for timestamp parameter $encParamName",
1048 "badtimestamp_{$encParamName}"
1052 return wfTimestamp( TS_MW
, $unixTimestamp );
1056 * Validate the supplied token.
1059 * @param string $token Supplied token
1060 * @param array $params All supplied parameters for the module
1062 * @throws MWException
1064 final public function validateToken( $token, array $params ) {
1065 $tokenType = $this->needsToken();
1066 $salts = ApiQueryTokens
::getTokenTypeSalts();
1067 if ( !isset( $salts[$tokenType] ) ) {
1068 throw new MWException(
1069 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1070 'without registering it'
1074 if ( $this->getUser()->matchEditToken(
1082 $webUiSalt = $this->getWebUITokenSalt( $params );
1083 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1095 * Validate and normalize of parameters of type 'user'
1096 * @param string $value Parameter value
1097 * @param string $encParamName Parameter name
1098 * @return string Validated and normalized parameter
1100 private function validateUser( $value, $encParamName ) {
1101 $title = Title
::makeTitleSafe( NS_USER
, $value );
1102 if ( $title === null ) {
1104 "Invalid value '$value' for user parameter $encParamName",
1105 "baduser_{$encParamName}"
1109 return $title->getText();
1114 /************************************************************************//**
1115 * @name Utility methods
1120 * Set a watch (or unwatch) based the based on a watchlist parameter.
1121 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1122 * @param Title $titleObj The article's title to change
1123 * @param string $userOption The user option to consider when $watch=preferences
1125 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1126 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1127 if ( $value === null ) {
1131 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1135 * Truncate an array to a certain length.
1136 * @param array $arr Array to truncate
1137 * @param int $limit Maximum length
1138 * @return bool True if the array was truncated, false otherwise
1140 public static function truncateArray( &$arr, $limit ) {
1142 while ( count( $arr ) > $limit ) {
1151 * Gets the user for whom to get the watchlist
1153 * @param array $params
1156 public function getWatchlistUser( $params ) {
1157 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1158 $user = User
::newFromName( $params['owner'], false );
1159 if ( !( $user && $user->getId() ) ) {
1160 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1162 $token = $user->getOption( 'watchlisttoken' );
1163 if ( $token == '' ||
$token != $params['token'] ) {
1165 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1170 if ( !$this->getUser()->isLoggedIn() ) {
1171 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1173 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1174 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1176 $user = $this->getUser();
1183 * A subset of wfEscapeWikiText for BC texts
1186 * @param string|array $v
1187 * @return string|array
1189 private static function escapeWikiText( $v ) {
1190 if ( is_array( $v ) ) {
1191 return array_map( 'self::escapeWikiText', $v );
1193 return strtr( $v, array(
1194 '__' => '__', '{' => '{', '}' => '}',
1195 '[[Category:' => '[[:Category:',
1196 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1202 * Create a Message from a string or array
1204 * A string is used as a message key. An array has the message key as the
1205 * first value and message parameters as subsequent values.
1208 * @param string|array|Message $msg
1209 * @param IContextSource $context
1210 * @param array $params
1211 * @return Message|null
1213 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1214 if ( is_string( $msg ) ) {
1215 $msg = wfMessage( $msg );
1216 } elseif ( is_array( $msg ) ) {
1217 $msg = call_user_func_array( 'wfMessage', $msg );
1219 if ( !$msg instanceof Message
) {
1223 $msg->setContext( $context );
1225 $msg->params( $params );
1233 /************************************************************************//**
1234 * @name Warning and error reporting
1239 * Set warning section for this module. Users should monitor this
1240 * section to notice any changes in API. Multiple calls to this
1241 * function will result in the warning messages being separated by
1243 * @param string $warning Warning message
1245 public function setWarning( $warning ) {
1246 $result = $this->getResult();
1247 $data = $result->getData();
1248 $moduleName = $this->getModuleName();
1249 if ( isset( $data['warnings'][$moduleName] ) ) {
1250 // Don't add duplicate warnings
1251 $oldWarning = $data['warnings'][$moduleName]['*'];
1252 $warnPos = strpos( $oldWarning, $warning );
1253 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1254 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1255 // Check if $warning is followed by "\n" or the end of the $oldWarning
1256 $warnPos +
= strlen( $warning );
1257 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1261 // If there is a warning already, append it to the existing one
1262 $warning = "$oldWarning\n$warning";
1265 ApiResult
::setContent( $msg, $warning );
1266 $result->addValue( 'warnings', $moduleName,
1267 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1271 * Adds a warning to the output, else dies
1273 * @param string $msg Message to show as a warning, or error message if dying
1274 * @param bool $enforceLimits Whether this is an enforce (die)
1276 private function warnOrDie( $msg, $enforceLimits = false ) {
1277 if ( $enforceLimits ) {
1278 $this->dieUsage( $msg, 'integeroutofrange' );
1281 $this->setWarning( $msg );
1285 * Throw a UsageException, which will (if uncaught) call the main module's
1286 * error handler and die with an error message.
1288 * @param string $description One-line human-readable description of the
1289 * error condition, e.g., "The API requires a valid action parameter"
1290 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1291 * automated identification of the error, e.g., 'unknown_action'
1292 * @param int $httpRespCode HTTP response code
1293 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1294 * @throws UsageException
1296 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1297 Profiler
::instance()->close();
1298 throw new UsageException(
1300 $this->encodeParamName( $errorCode ),
1307 * Get error (as code, string) from a Status object.
1310 * @param Status $status
1311 * @return array Array of code and error string
1312 * @throws MWException
1314 public function getErrorFromStatus( $status ) {
1315 if ( $status->isGood() ) {
1316 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1319 $errors = $status->getErrorsArray();
1321 // No errors? Assume the warnings should be treated as errors
1322 $errors = $status->getWarningsArray();
1325 // Still no errors? Punt
1326 $errors = array( array( 'unknownerror-nocode' ) );
1329 // Cannot use dieUsageMsg() because extensions might return custom
1331 if ( $errors[0] instanceof Message
) {
1333 $code = $msg->getKey();
1335 $code = array_shift( $errors[0] );
1336 $msg = wfMessage( $code, $errors[0] );
1338 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1339 // Translate message to code, for backwards compatibility
1340 $code = ApiBase
::$messageMap[$code]['code'];
1343 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1347 * Throw a UsageException based on the errors in the Status object.
1350 * @param Status $status
1351 * @throws MWException
1353 public function dieStatus( $status ) {
1355 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1356 $this->dieUsage( $msg, $code );
1359 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1361 * Array that maps message keys to error messages. $1 and friends are replaced.
1363 public static $messageMap = array(
1364 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1365 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1366 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1368 // Messages from Title::getUserPermissionsErrors()
1369 'ns-specialprotected' => array(
1370 'code' => 'unsupportednamespace',
1371 'info' => "Pages in the Special namespace can't be edited"
1373 'protectedinterface' => array(
1374 'code' => 'protectednamespace-interface',
1375 'info' => "You're not allowed to edit interface messages"
1377 'namespaceprotected' => array(
1378 'code' => 'protectednamespace',
1379 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1381 'customcssprotected' => array(
1382 'code' => 'customcssprotected',
1383 'info' => "You're not allowed to edit custom CSS pages"
1385 'customjsprotected' => array(
1386 'code' => 'customjsprotected',
1387 'info' => "You're not allowed to edit custom JavaScript pages"
1389 'cascadeprotected' => array(
1390 'code' => 'cascadeprotected',
1391 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1393 'protectedpagetext' => array(
1394 'code' => 'protectedpage',
1395 'info' => "The \"\$1\" right is required to edit this page"
1397 'protect-cantedit' => array(
1398 'code' => 'cantedit',
1399 'info' => "You can't protect this page because you can't edit it"
1401 'deleteprotected' => array(
1402 'code' => 'cantedit',
1403 'info' => "You can't delete this page because it has been protected"
1405 'badaccess-group0' => array(
1406 'code' => 'permissiondenied',
1407 'info' => "Permission denied"
1408 ), // Generic permission denied message
1409 'badaccess-groups' => array(
1410 'code' => 'permissiondenied',
1411 'info' => "Permission denied"
1413 'titleprotected' => array(
1414 'code' => 'protectedtitle',
1415 'info' => "This title has been protected from creation"
1417 'nocreate-loggedin' => array(
1418 'code' => 'cantcreate',
1419 'info' => "You don't have permission to create new pages"
1421 'nocreatetext' => array(
1422 'code' => 'cantcreate-anon',
1423 'info' => "Anonymous users can't create new pages"
1425 'movenologintext' => array(
1426 'code' => 'cantmove-anon',
1427 'info' => "Anonymous users can't move pages"
1429 'movenotallowed' => array(
1430 'code' => 'cantmove',
1431 'info' => "You don't have permission to move pages"
1433 'confirmedittext' => array(
1434 'code' => 'confirmemail',
1435 'info' => "You must confirm your email address before you can edit"
1437 'blockedtext' => array(
1438 'code' => 'blocked',
1439 'info' => "You have been blocked from editing"
1441 'autoblockedtext' => array(
1442 'code' => 'autoblocked',
1443 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1446 // Miscellaneous interface messages
1447 'actionthrottledtext' => array(
1448 'code' => 'ratelimited',
1449 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1451 'alreadyrolled' => array(
1452 'code' => 'alreadyrolled',
1453 'info' => "The page you tried to rollback was already rolled back"
1455 'cantrollback' => array(
1456 'code' => 'onlyauthor',
1457 'info' => "The page you tried to rollback only has one author"
1459 'readonlytext' => array(
1460 'code' => 'readonly',
1461 'info' => "The wiki is currently in read-only mode"
1463 'sessionfailure' => array(
1464 'code' => 'badtoken',
1465 'info' => "Invalid token" ),
1466 'cannotdelete' => array(
1467 'code' => 'cantdelete',
1468 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1470 'notanarticle' => array(
1471 'code' => 'missingtitle',
1472 'info' => "The page you requested doesn't exist"
1474 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1476 'immobile_namespace' => array(
1477 'code' => 'immobilenamespace',
1478 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1480 'articleexists' => array(
1481 'code' => 'articleexists',
1482 'info' => "The destination article already exists and is not a redirect to the source article"
1484 'protectedpage' => array(
1485 'code' => 'protectedpage',
1486 'info' => "You don't have permission to perform this move"
1488 'hookaborted' => array(
1489 'code' => 'hookaborted',
1490 'info' => "The modification you tried to make was aborted by an extension hook"
1492 'cantmove-titleprotected' => array(
1493 'code' => 'protectedtitle',
1494 'info' => "The destination article has been protected from creation"
1496 'imagenocrossnamespace' => array(
1497 'code' => 'nonfilenamespace',
1498 'info' => "Can't move a file to a non-file namespace"
1500 'imagetypemismatch' => array(
1501 'code' => 'filetypemismatch',
1502 'info' => "The new file extension doesn't match its type"
1504 // 'badarticleerror' => shouldn't happen
1505 // 'badtitletext' => shouldn't happen
1506 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1507 'range_block_disabled' => array(
1508 'code' => 'rangedisabled',
1509 'info' => "Blocking IP ranges has been disabled"
1511 'nosuchusershort' => array(
1512 'code' => 'nosuchuser',
1513 'info' => "The user you specified doesn't exist"
1515 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1516 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1517 'ipb_already_blocked' => array(
1518 'code' => 'alreadyblocked',
1519 'info' => "The user you tried to block was already blocked"
1521 'ipb_blocked_as_range' => array(
1522 'code' => 'blockedasrange',
1523 '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."
1525 'ipb_cant_unblock' => array(
1526 'code' => 'cantunblock',
1527 'info' => "The block you specified was not found. It may have been unblocked already"
1529 'mailnologin' => array(
1530 'code' => 'cantsend',
1531 '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"
1533 'ipbblocked' => array(
1534 'code' => 'ipbblocked',
1535 'info' => 'You cannot block or unblock users while you are yourself blocked'
1537 'ipbnounblockself' => array(
1538 'code' => 'ipbnounblockself',
1539 'info' => 'You are not allowed to unblock yourself'
1541 'usermaildisabled' => array(
1542 'code' => 'usermaildisabled',
1543 'info' => "User email has been disabled"
1545 'blockedemailuser' => array(
1546 'code' => 'blockedfrommail',
1547 'info' => "You have been blocked from sending email"
1549 'notarget' => array(
1550 'code' => 'notarget',
1551 'info' => "You have not specified a valid target for this action"
1554 'code' => 'noemail',
1555 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1557 'rcpatroldisabled' => array(
1558 'code' => 'patroldisabled',
1559 'info' => "Patrolling is disabled on this wiki"
1561 'markedaspatrollederror-noautopatrol' => array(
1562 'code' => 'noautopatrol',
1563 'info' => "You don't have permission to patrol your own changes"
1565 'delete-toobig' => array(
1566 'code' => 'bigdelete',
1567 'info' => "You can't delete this page because it has more than \$1 revisions"
1569 'movenotallowedfile' => array(
1570 'code' => 'cantmovefile',
1571 'info' => "You don't have permission to move files"
1573 'userrights-no-interwiki' => array(
1574 'code' => 'nointerwikiuserrights',
1575 'info' => "You don't have permission to change user rights on other wikis"
1577 'userrights-nodatabase' => array(
1578 'code' => 'nosuchdatabase',
1579 'info' => "Database \"\$1\" does not exist or is not local"
1581 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1582 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1583 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1584 'import-rootpage-invalid' => array(
1585 'code' => 'import-rootpage-invalid',
1586 'info' => 'Root page is an invalid title'
1588 'import-rootpage-nosubpage' => array(
1589 'code' => 'import-rootpage-nosubpage',
1590 'info' => 'Namespace "$1" of the root page does not allow subpages'
1593 // API-specific messages
1594 'readrequired' => array(
1595 'code' => 'readapidenied',
1596 'info' => "You need read permission to use this module"
1598 'writedisabled' => array(
1599 'code' => 'noapiwrite',
1600 '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"
1602 'writerequired' => array(
1603 'code' => 'writeapidenied',
1604 'info' => "You're not allowed to edit this wiki through the API"
1606 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1607 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1608 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1609 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1610 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1611 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1612 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1613 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1614 'create-titleexists' => array(
1615 'code' => 'create-titleexists',
1616 'info' => "Existing titles can't be protected with 'create'"
1618 'missingtitle-createonly' => array(
1619 'code' => 'missingtitle-createonly',
1620 'info' => "Missing titles can only be protected with 'create'"
1622 'cantblock' => array( 'code' => 'cantblock',
1623 'info' => "You don't have permission to block users"
1625 'canthide' => array(
1626 'code' => 'canthide',
1627 'info' => "You don't have permission to hide user names from the block log"
1629 'cantblock-email' => array(
1630 'code' => 'cantblock-email',
1631 'info' => "You don't have permission to block users from sending email through the wiki"
1633 'unblock-notarget' => array(
1634 'code' => 'notarget',
1635 'info' => "Either the id or the user parameter must be set"
1637 'unblock-idanduser' => array(
1638 'code' => 'idanduser',
1639 'info' => "The id and user parameters can't be used together"
1641 'cantunblock' => array(
1642 'code' => 'permissiondenied',
1643 'info' => "You don't have permission to unblock users"
1645 'cannotundelete' => array(
1646 'code' => 'cantundelete',
1647 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1649 'permdenied-undelete' => array(
1650 'code' => 'permissiondenied',
1651 'info' => "You don't have permission to restore deleted revisions"
1653 'createonly-exists' => array(
1654 'code' => 'articleexists',
1655 'info' => "The article you tried to create has been created already"
1657 'nocreate-missing' => array(
1658 'code' => 'missingtitle',
1659 'info' => "The article you tried to edit doesn't exist"
1661 'cantchangecontentmodel' => array(
1662 'code' => 'cantchangecontentmodel',
1663 'info' => "You don't have permission to change the content model of a page"
1665 'nosuchrcid' => array(
1666 'code' => 'nosuchrcid',
1667 'info' => "There is no change with rcid \"\$1\""
1669 'protect-invalidaction' => array(
1670 'code' => 'protect-invalidaction',
1671 'info' => "Invalid protection type \"\$1\""
1673 'protect-invalidlevel' => array(
1674 'code' => 'protect-invalidlevel',
1675 'info' => "Invalid protection level \"\$1\""
1677 'toofewexpiries' => array(
1678 'code' => 'toofewexpiries',
1679 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1681 'cantimport' => array(
1682 'code' => 'cantimport',
1683 'info' => "You don't have permission to import pages"
1685 'cantimport-upload' => array(
1686 'code' => 'cantimport-upload',
1687 'info' => "You don't have permission to import uploaded pages"
1689 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1690 'importuploaderrorsize' => array(
1691 'code' => 'filetoobig',
1692 'info' => 'The file you uploaded is bigger than the maximum upload size'
1694 'importuploaderrorpartial' => array(
1695 'code' => 'partialupload',
1696 'info' => 'The file was only partially uploaded'
1698 'importuploaderrortemp' => array(
1699 'code' => 'notempdir',
1700 'info' => 'The temporary upload directory is missing'
1702 'importcantopen' => array(
1703 'code' => 'cantopenfile',
1704 'info' => "Couldn't open the uploaded file"
1706 'import-noarticle' => array(
1707 'code' => 'badinterwiki',
1708 'info' => 'Invalid interwiki title specified'
1710 'importbadinterwiki' => array(
1711 'code' => 'badinterwiki',
1712 'info' => 'Invalid interwiki title specified'
1714 'import-unknownerror' => array(
1715 'code' => 'import-unknownerror',
1716 'info' => "Unknown error on import: \"\$1\""
1718 'cantoverwrite-sharedfile' => array(
1719 'code' => 'cantoverwrite-sharedfile',
1720 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1722 'sharedfile-exists' => array(
1723 'code' => 'fileexists-sharedrepo-perm',
1724 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1726 'mustbeposted' => array(
1727 'code' => 'mustbeposted',
1728 'info' => "The \$1 module requires a POST request"
1732 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1734 'specialpage-cantexecute' => array(
1735 'code' => 'specialpage-cantexecute',
1736 'info' => "You don't have permission to view the results of this special page"
1738 'invalidoldimage' => array(
1739 'code' => 'invalidoldimage',
1740 'info' => 'The oldimage parameter has invalid format'
1742 'nodeleteablefile' => array(
1743 'code' => 'nodeleteablefile',
1744 'info' => 'No such old version of the file'
1746 'fileexists-forbidden' => array(
1747 'code' => 'fileexists-forbidden',
1748 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1750 'fileexists-shared-forbidden' => array(
1751 'code' => 'fileexists-shared-forbidden',
1752 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1754 'filerevert-badversion' => array(
1755 'code' => 'filerevert-badversion',
1756 'info' => 'There is no previous local version of this file with the provided timestamp.'
1759 // ApiEditPage messages
1760 'noimageredirect-anon' => array(
1761 'code' => 'noimageredirect-anon',
1762 'info' => "Anonymous users can't create image redirects"
1764 'noimageredirect-logged' => array(
1765 'code' => 'noimageredirect',
1766 'info' => "You don't have permission to create image redirects"
1768 'spamdetected' => array(
1769 'code' => 'spamdetected',
1770 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1772 'contenttoobig' => array(
1773 'code' => 'contenttoobig',
1774 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1776 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1777 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1778 'wasdeleted' => array(
1779 'code' => 'pagedeleted',
1780 'info' => "The page has been deleted since you fetched its timestamp"
1782 'blankpage' => array(
1783 'code' => 'emptypage',
1784 'info' => "Creating new, empty pages is not allowed"
1786 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1787 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1788 'missingtext' => array(
1790 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1792 'emptynewsection' => array(
1793 'code' => 'emptynewsection',
1794 'info' => 'Creating empty new sections is not possible.'
1796 'revwrongpage' => array(
1797 'code' => 'revwrongpage',
1798 'info' => "r\$1 is not a revision of \"\$2\""
1800 'undo-failure' => array(
1801 'code' => 'undofailure',
1802 'info' => 'Undo failed due to conflicting intermediate edits'
1804 'content-not-allowed-here' => array(
1805 'code' => 'contentnotallowedhere',
1806 'info' => 'Content model "$1" is not allowed at title "$2"'
1809 // Messages from WikiPage::doEit()
1810 'edit-hook-aborted' => array(
1811 'code' => 'edit-hook-aborted',
1812 'info' => "Your edit was aborted by an ArticleSave hook"
1814 'edit-gone-missing' => array(
1815 'code' => 'edit-gone-missing',
1816 'info' => "The page you tried to edit doesn't seem to exist anymore"
1818 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1819 'edit-already-exists' => array(
1820 'code' => 'edit-already-exists',
1821 'info' => 'It seems the page you tried to create already exist'
1825 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1826 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1827 'uploaddisabled' => array(
1828 'code' => 'uploaddisabled',
1829 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1831 'copyuploaddisabled' => array(
1832 'code' => 'copyuploaddisabled',
1833 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1835 'copyuploadbaddomain' => array(
1836 'code' => 'copyuploadbaddomain',
1837 'info' => 'Uploads by URL are not allowed from this domain.'
1839 'copyuploadbadurl' => array(
1840 'code' => 'copyuploadbadurl',
1841 'info' => 'Upload not allowed from this URL.'
1844 'filename-tooshort' => array(
1845 'code' => 'filename-tooshort',
1846 'info' => 'The filename is too short'
1848 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1849 'illegal-filename' => array(
1850 'code' => 'illegal-filename',
1851 'info' => 'The filename is not allowed'
1853 'filetype-missing' => array(
1854 'code' => 'filetype-missing',
1855 'info' => 'The file is missing an extension'
1858 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1860 // @codingStandardsIgnoreEnd
1863 * Helper function for readonly errors
1865 public function dieReadOnly() {
1866 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1867 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1868 array( 'readonlyreason' => wfReadOnlyReason() ) );
1872 * Output the error message related to a certain array
1873 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1875 public function dieUsageMsg( $error ) {
1876 # most of the time we send a 1 element, so we might as well send it as
1877 # a string and make this an array here.
1878 if ( is_string( $error ) ) {
1879 $error = array( $error );
1881 $parsed = $this->parseMsg( $error );
1882 $this->dieUsage( $parsed['info'], $parsed['code'] );
1886 * Will only set a warning instead of failing if the global $wgDebugAPI
1887 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1888 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1891 public function dieUsageMsgOrDebug( $error ) {
1892 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1893 $this->dieUsageMsg( $error );
1896 if ( is_string( $error ) ) {
1897 $error = array( $error );
1899 $parsed = $this->parseMsg( $error );
1900 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1904 * Die with the $prefix.'badcontinue' error. This call is common enough to
1905 * make it into the base method.
1906 * @param bool $condition Will only die if this value is true
1909 protected function dieContinueUsageIf( $condition ) {
1912 'Invalid continue param. You should pass the original value returned by the previous query',
1918 * Return the error message related to a certain array
1919 * @param array $error Element of a getUserPermissionsErrors()-style array
1920 * @return array('code' => code, 'info' => info)
1922 public function parseMsg( $error ) {
1923 $error = (array)$error; // It seems strings sometimes make their way in here
1924 $key = array_shift( $error );
1926 // Check whether the error array was nested
1927 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1928 if ( is_array( $key ) ) {
1930 $key = array_shift( $error );
1933 if ( isset( self
::$messageMap[$key] ) ) {
1935 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1936 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1940 // If the key isn't present, throw an "unknown error"
1941 return $this->parseMsg( array( 'unknownerror', $key ) );
1945 * Internal code errors should be reported with this method
1946 * @param string $method Method or function name
1947 * @param string $message Error message
1948 * @throws MWException
1950 protected static function dieDebug( $method, $message ) {
1951 throw new MWException( "Internal error in $method: $message" );
1956 /************************************************************************//**
1957 * @name Help message generation
1962 * Return the description message.
1964 * @return string|array|Message
1966 protected function getDescriptionMessage() {
1967 return "apihelp-{$this->getModulePath()}-description";
1971 * Get final module description, after hooks have had a chance to tweak it as
1974 * @since 1.25, returns Message[] rather than string[]
1977 public function getFinalDescription() {
1978 $desc = $this->getDescription();
1979 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
1980 $desc = self
::escapeWikiText( $desc );
1981 if ( is_array( $desc ) ) {
1982 $desc = join( "\n", $desc );
1984 $desc = (string)$desc;
1987 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1988 $this->getModulePrefix(),
1989 $this->getModuleName(),
1990 $this->getModulePath(),
1992 if ( !$msg->exists() ) {
1993 $msg = $this->msg( 'api-help-fallback-description', $desc );
1995 $msgs = array( $msg );
1997 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2003 * Get final list of parameters, after hooks have had a chance to
2004 * tweak it as needed.
2006 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2007 * @return array|bool False on no parameters
2008 * @since 1.21 $flags param added
2010 public function getFinalParams( $flags = 0 ) {
2011 $params = $this->getAllowedParams( $flags );
2016 if ( $this->needsToken() ) {
2017 $params['token'] = array(
2018 ApiBase
::PARAM_TYPE
=> 'string',
2019 ApiBase
::PARAM_REQUIRED
=> true,
2020 ApiBase
::PARAM_HELP_MSG
=> array(
2021 'api-help-param-token',
2022 $this->needsToken(),
2024 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2027 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2033 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2036 * @since 1.25, returns array of Message[] rather than array of string[]
2037 * @return array Keys are parameter names, values are arrays of Message objects
2039 public function getFinalParamDescription() {
2040 $prefix = $this->getModulePrefix();
2041 $name = $this->getModuleName();
2042 $path = $this->getModulePath();
2044 $desc = $this->getParamDescription();
2045 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2050 $desc = self
::escapeWikiText( $desc );
2052 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2054 foreach ( $params as $param => $settings ) {
2055 if ( !is_array( $settings ) ) {
2056 $settings = array();
2059 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2060 if ( is_array( $d ) ) {
2061 // Special handling for prop parameters
2062 $d = array_map( function ( $line ) {
2063 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2064 $line = "\n;{$m[1]}:{$m[2]}";
2068 $d = join( ' ', $d );
2071 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2072 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2074 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2075 if ( !$msg->exists() ) {
2076 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2079 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2080 array( $prefix, $param, $name, $path ) );
2082 $this->dieDebug( __METHOD__
,
2083 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2085 $msgs[$param] = array( $msg );
2087 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2088 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2089 $this->dieDebug( __METHOD__
,
2090 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2092 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2093 $this->dieDebug( __METHOD__
,
2094 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2095 'ApiBase::PARAM_TYPE is an array' );
2098 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2099 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2100 if ( isset( $valueMsgs[$value] ) ) {
2101 $msg = $valueMsgs[$value];
2103 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2105 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2106 array( $prefix, $param, $name, $path, $value ) );
2108 $m = new ApiHelpParamValueMessage(
2110 array( $m->getKey(), 'api-help-param-no-description' ),
2113 $msgs[$param][] = $m->setContext( $this->getContext() );
2115 $this->dieDebug( __METHOD__
,
2116 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2121 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2122 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2123 $this->dieDebug( __METHOD__
,
2124 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2126 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2127 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2128 array( $prefix, $param, $name, $path ) );
2130 $msgs[$param][] = $m;
2132 $this->dieDebug( __METHOD__
,
2133 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2139 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2145 * Generates the list of flags for the help screen and for action=paraminfo
2147 * Corresponding messages: api-help-flag-deprecated,
2148 * api-help-flag-internal, api-help-flag-readrights,
2149 * api-help-flag-writerights, api-help-flag-mustbeposted
2153 protected function getHelpFlags() {
2156 if ( $this->isDeprecated() ) {
2157 $flags[] = 'deprecated';
2159 if ( $this->isInternal() ) {
2160 $flags[] = 'internal';
2162 if ( $this->isReadMode() ) {
2163 $flags[] = 'readrights';
2165 if ( $this->isWriteMode() ) {
2166 $flags[] = 'writerights';
2168 if ( $this->mustBePosted() ) {
2169 $flags[] = 'mustbeposted';
2176 * Called from ApiHelp before the pieces are joined together and returned.
2178 * This exists mainly for ApiMain to add the Permissions and Credits
2179 * sections. Other modules probably don't need it.
2181 * @param string[] &$help Array of help data
2182 * @param array $options Options passed to ApiHelp::getHelp
2184 public function modifyHelp( array &$help, array $options ) {
2189 /************************************************************************//**
2195 * Profiling: total module execution time
2197 private $mTimeIn = 0, $mModuleTime = 0;
2198 /** @var ScopedCallback */
2200 /** @var ScopedCallback */
2204 * Get the name of the module as shown in the profiler log
2206 * @param DatabaseBase|bool $db
2210 public function getModuleProfileName( $db = false ) {
2212 return 'API:' . $this->mModuleName
. '-DB';
2215 return 'API:' . $this->mModuleName
;
2219 * Start module profiling
2221 public function profileIn() {
2222 if ( $this->mTimeIn
!== 0 ) {
2223 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2225 $this->mTimeIn
= microtime( true );
2226 $this->profile
= Profiler
::instance()->scopedProfileIn( $this->getModuleProfileName() );
2230 * End module profiling
2232 public function profileOut() {
2233 if ( $this->mTimeIn
=== 0 ) {
2234 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2236 if ( $this->mDBTimeIn
!== 0 ) {
2239 'Must be called after database profiling is done with profileDBOut()'
2243 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2245 Profiler
::instance()->scopedProfileOut( $this->profile
);
2249 * When modules crash, sometimes it is needed to do a profileOut() regardless
2250 * of the profiling state the module was in. This method does such cleanup.
2252 public function safeProfileOut() {
2253 if ( $this->mTimeIn
!== 0 ) {
2254 if ( $this->mDBTimeIn
!== 0 ) {
2255 $this->profileDBOut();
2257 $this->profileOut();
2262 * Total time the module was executed
2265 public function getProfileTime() {
2266 if ( $this->mTimeIn
!== 0 ) {
2267 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2270 return $this->mModuleTime
;
2274 * Profiling: database execution time
2276 private $mDBTimeIn = 0, $mDBTime = 0;
2279 * Start module profiling
2281 public function profileDBIn() {
2282 if ( $this->mTimeIn
=== 0 ) {
2285 'Must be called while profiling the entire module with profileIn()'
2288 if ( $this->mDBTimeIn
!== 0 ) {
2289 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2291 $this->mDBTimeIn
= microtime( true );
2293 $this->dbProfile
= Profiler
::instance()->scopedProfileIn( $this->getModuleProfileName( true ) );
2297 * End database profiling
2299 public function profileDBOut() {
2300 if ( $this->mTimeIn
=== 0 ) {
2301 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2302 'the entire module with profileIn()' );
2304 if ( $this->mDBTimeIn
=== 0 ) {
2305 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2308 $time = microtime( true ) - $this->mDBTimeIn
;
2309 $this->mDBTimeIn
= 0;
2311 $this->mDBTime +
= $time;
2312 $this->getMain()->mDBTime +
= $time;
2313 Profiler
::instance()->scopedProfileOut( $this->dbProfile
);
2317 * Total time the module used the database
2320 public function getProfileDBTime() {
2321 if ( $this->mDBTimeIn
!== 0 ) {
2322 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2325 return $this->mDBTime
;
2329 * Write logging information for API features to a debug log, for usage
2331 * @param string $feature Feature being used.
2333 protected function logFeatureUsage( $feature ) {
2334 $request = $this->getRequest();
2335 $s = '"' . addslashes( $feature ) . '"' .
2336 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2337 ' "' . $request->getIP() . '"' .
2338 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2339 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2340 wfDebugLog( 'api-feature-usage', $s, 'private' );
2345 /************************************************************************//**
2350 /// @deprecated since 1.24
2351 const PROP_ROOT
= 'ROOT';
2352 /// @deprecated since 1.24
2353 const PROP_LIST
= 'LIST';
2354 /// @deprecated since 1.24
2355 const PROP_TYPE
= 0;
2356 /// @deprecated since 1.24
2357 const PROP_NULLABLE
= 1;
2360 * Formerly returned a string that identifies the version of the extending
2361 * class. Typically included the class name, the svn revision, timestamp,
2362 * and last author. Usually done with SVN's Id keyword
2364 * @deprecated since 1.21, version string is no longer supported
2367 public function getVersion() {
2368 wfDeprecated( __METHOD__
, '1.21' );
2373 * Formerly used to fetch a list of possible properites in the result,
2374 * somehow organized with respect to the prop parameter that causes them to
2375 * be returned. The specific semantics of the return value was never
2376 * specified. Since this was never possible to be accurately updated, it
2379 * @deprecated since 1.24
2380 * @return array|bool
2382 protected function getResultProperties() {
2383 wfDeprecated( __METHOD__
, '1.24' );
2388 * @see self::getResultProperties()
2389 * @deprecated since 1.24
2390 * @return array|bool
2392 public function getFinalResultProperties() {
2393 wfDeprecated( __METHOD__
, '1.24' );
2398 * @see self::getResultProperties()
2399 * @deprecated since 1.24
2401 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2402 wfDeprecated( __METHOD__
, '1.24' );
2406 * @see self::getPossibleErrors()
2407 * @deprecated since 1.24
2410 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2411 wfDeprecated( __METHOD__
, '1.24' );
2416 * @see self::getPossibleErrors()
2417 * @deprecated since 1.24
2420 public function getRequireMaxOneParameterErrorMessages( $params ) {
2421 wfDeprecated( __METHOD__
, '1.24' );
2426 * @see self::getPossibleErrors()
2427 * @deprecated since 1.24
2430 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2431 wfDeprecated( __METHOD__
, '1.24' );
2436 * @see self::getPossibleErrors()
2437 * @deprecated since 1.24
2440 public function getTitleOrPageIdErrorMessage() {
2441 wfDeprecated( __METHOD__
, '1.24' );
2446 * This formerly attempted to return a list of all possible errors returned
2447 * by the module. However, this was impossible to maintain in many cases
2448 * since errors could come from other areas of MediaWiki and in some cases
2449 * from arbitrary extension hooks. Since a partial list claiming to be
2450 * comprehensive is unlikely to be useful, it was removed.
2452 * @deprecated since 1.24
2455 public function getPossibleErrors() {
2456 wfDeprecated( __METHOD__
, '1.24' );
2461 * @see self::getPossibleErrors()
2462 * @deprecated since 1.24
2465 public function getFinalPossibleErrors() {
2466 wfDeprecated( __METHOD__
, '1.24' );
2471 * @see self::getPossibleErrors()
2472 * @deprecated since 1.24
2475 public function parseErrors( $errors ) {
2476 wfDeprecated( __METHOD__
, '1.24' );
2481 * Returns the description string for this module
2483 * Ignored if an i18n message exists for
2484 * "apihelp-{$this->getModulePathString()}-description".
2486 * @deprecated since 1.25
2487 * @return Message|string|array
2489 protected function getDescription() {
2494 * Returns an array of parameter descriptions.
2496 * For each parameter, ignored if an i18n message exists for the parameter.
2497 * By default that message is
2498 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2499 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2500 * self::getFinalParams().
2502 * @deprecated since 1.25
2503 * @return array|bool False on no parameter descriptions
2505 protected function getParamDescription() {
2510 * Returns usage examples for this module.
2512 * Return value as an array is either:
2513 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2515 * - sequential numeric keys with even-numbered keys being display-text
2516 * and odd-numbered keys being partial urls
2517 * - partial URLs as keys with display-text (string or array-to-be-joined)
2519 * Return value as a string is the same as an array with a numeric key and
2520 * that value, and boolean false means "no examples".
2522 * @deprecated since 1.25, use getExamplesMessages() instead
2523 * @return bool|string|array
2525 protected function getExamples() {
2530 * Generates help message for this module, or false if there is no description
2531 * @deprecated since 1.25
2532 * @return string|bool
2534 public function makeHelpMsg() {
2535 wfDeprecated( __METHOD__
, '1.25' );
2536 static $lnPrfx = "\n ";
2538 $msg = $this->getFinalDescription();
2540 if ( $msg !== false ) {
2542 if ( !is_array( $msg ) ) {
2547 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2549 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2551 if ( $this->isReadMode() ) {
2552 $msg .= "\nThis module requires read rights";
2554 if ( $this->isWriteMode() ) {
2555 $msg .= "\nThis module requires write rights";
2557 if ( $this->mustBePosted() ) {
2558 $msg .= "\nThis module only accepts POST requests";
2560 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2561 $this->mustBePosted()
2567 $paramsMsg = $this->makeHelpMsgParameters();
2568 if ( $paramsMsg !== false ) {
2569 $msg .= "Parameters:\n$paramsMsg";
2572 $examples = $this->getExamples();
2574 if ( !is_array( $examples ) ) {
2579 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2580 foreach ( $examples as $k => $v ) {
2581 if ( is_numeric( $k ) ) {
2584 if ( is_array( $v ) ) {
2585 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2587 $msgExample = " $v";
2590 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2600 * @deprecated since 1.25
2601 * @param string $item
2604 private function indentExampleText( $item ) {
2609 * @deprecated since 1.25
2610 * @param string $prefix Text to split output items
2611 * @param string $title What is being output
2612 * @param string|array $input
2615 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2616 wfDeprecated( __METHOD__
, '1.25' );
2617 if ( $input === false ) {
2620 if ( !is_array( $input ) ) {
2621 $input = array( $input );
2624 if ( count( $input ) > 0 ) {
2626 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2630 $msg .= implode( $prefix, $input ) . "\n";
2639 * Generates the parameter descriptions for this module, to be displayed in the
2641 * @deprecated since 1.25
2642 * @return string|bool
2644 public function makeHelpMsgParameters() {
2645 wfDeprecated( __METHOD__
, '1.25' );
2646 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2649 $paramsDescription = $this->getFinalParamDescription();
2651 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2652 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2653 foreach ( $params as $paramName => $paramSettings ) {
2654 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2655 if ( is_array( $desc ) ) {
2656 $desc = implode( $paramPrefix, $desc );
2660 if ( !is_array( $paramSettings ) ) {
2661 $paramSettings = array(
2662 self
::PARAM_DFLT
=> $paramSettings,
2666 //handle missing type
2667 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2668 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2669 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2671 if ( is_bool( $dflt ) ) {
2672 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2673 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2674 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2675 } elseif ( is_int( $dflt ) ) {
2676 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2680 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2681 && $paramSettings[self
::PARAM_DEPRECATED
]
2683 $desc = "DEPRECATED! $desc";
2686 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2687 && $paramSettings[self
::PARAM_REQUIRED
]
2689 $desc .= $paramPrefix . "This parameter is required";
2692 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2693 ?
$paramSettings[self
::PARAM_TYPE
]
2695 if ( isset( $type ) ) {
2696 $hintPipeSeparated = true;
2697 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2698 ?
$paramSettings[self
::PARAM_ISMULTI
]
2701 $prompt = 'Values (separate with \'|\'): ';
2703 $prompt = 'One value: ';
2706 if ( $type === 'submodule' ) {
2707 $type = $this->getModuleManager()->getNames( $paramName );
2710 if ( is_array( $type ) ) {
2712 $nothingPrompt = '';
2713 foreach ( $type as $t ) {
2715 $nothingPrompt = 'Can be empty, or ';
2720 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2721 $choicesstring = implode( ', ', $choices );
2722 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2723 $hintPipeSeparated = false;
2727 // Special handling because namespaces are
2728 // type-limited, yet they are not given
2729 $desc .= $paramPrefix . $prompt;
2730 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2731 100, $descWordwrap );
2732 $hintPipeSeparated = false;
2735 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2736 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2737 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2739 $desc .= ' allowed';
2742 $s = $multi ?
's' : '';
2743 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2744 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2745 if ( $hasMin ||
$hasMax ) {
2747 $intRangeStr = "The value$s must be no less than " .
2748 "{$paramSettings[self::PARAM_MIN]}";
2749 } elseif ( !$hasMin ) {
2750 $intRangeStr = "The value$s must be no more than " .
2751 "{$paramSettings[self::PARAM_MAX]}";
2753 $intRangeStr = "The value$s must be between " .
2754 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2757 $desc .= $paramPrefix . $intRangeStr;
2761 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2767 if ( $hintPipeSeparated ) {
2768 $desc .= $paramPrefix . "Separate values with '|'";
2771 $isArray = is_array( $type );
2773 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2775 $desc .= $paramPrefix . "Maximum number of values " .
2776 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2781 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2782 if ( !is_null( $default ) && $default !== false ) {
2783 $desc .= $paramPrefix . "Default: $default";
2786 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2799 * For really cool vim folding this needs to be at the end:
2800 * vim: foldmarker=@{,@} foldmethod=marker