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 can be a string key, an array giving key and parameters, or a
71 const PARAM_HELP_MSG
= 10;
73 // Specify additional i18n messages to append to the normal message. Value
74 // is an array of any of strings giving the message key, arrays giving key and
75 // parameters, or Message objects.
76 const PARAM_HELP_MSG_APPEND
= 11;
78 // Specify additional information tags for the parameter. Value is an array
79 // of arrays, with the first member being the 'tag' for the info and the
80 // remaining members being the values. In the help, this is formatted using
81 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
82 // comma-joined list of values, $3 = module prefix.
83 const PARAM_HELP_MSG_INFO
= 12;
85 // When PARAM_DFLT is an array, this may be an array mapping those values
86 // to page titles which will be linked in the help.
87 const PARAM_VALUE_LINKS
= 13;
89 const LIMIT_BIG1
= 500; // Fast query, std user limit
90 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
91 const LIMIT_SML1
= 50; // Slow query, std user limit
92 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
95 * getAllowedParams() flag: When set, the result could take longer to generate,
96 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
99 const GET_VALUES_FOR_HELP
= 1;
102 private $mMainModule;
104 private $mModuleName, $mModulePrefix;
105 private $mSlaveDB = null;
106 private $mParamCache = array();
109 * @param ApiMain $mainModule
110 * @param string $moduleName Name of this module
111 * @param string $modulePrefix Prefix to use for parameter names
113 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
114 $this->mMainModule
= $mainModule;
115 $this->mModuleName
= $moduleName;
116 $this->mModulePrefix
= $modulePrefix;
118 if ( !$this->isMain() ) {
119 $this->setContext( $mainModule->getContext() );
124 /************************************************************************//**
125 * @name Methods to implement
130 * Evaluates the parameters, performs the requested query, and sets up
131 * the result. Concrete implementations of ApiBase must override this
132 * method to provide whatever functionality their module offers.
133 * Implementations must not produce any output on their own and are not
134 * expected to handle any errors.
136 * The execute() method will be invoked directly by ApiMain immediately
137 * before the result of the module is output. Aside from the
138 * constructor, implementations should assume that no other methods
139 * will be called externally on the module before the result is
142 * The result data should be stored in the ApiResult object available
143 * through getResult().
145 abstract public function execute();
148 * Get the module manager, or null if this module has no sub-modules
150 * @return ApiModuleManager
152 public function getModuleManager() {
157 * If the module may only be used with a certain format module,
158 * it should override this method to return an instance of that formatter.
159 * A value of null means the default format will be used.
160 * @return mixed Instance of a derived class of ApiFormatBase, or null
162 public function getCustomPrinter() {
167 * Returns usage examples for this module.
169 * Return value has query strings as keys, with values being either strings
170 * (message key), arrays (message key + parameter), or Message objects.
172 * Do not call this base class implementation when overriding this method.
177 protected function getExamplesMessages() {
178 // Fall back to old non-localised method
181 $examples = $this->getExamples();
183 if ( !is_array( $examples ) ) {
184 $examples = array( $examples );
185 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
186 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
187 !preg_match( '/^\s*api\.php\?/', $examples[0] )
189 // Fix up the ugly "even numbered elements are description, odd
190 // numbered elemts are the link" format (see doc for self::getExamples)
192 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
193 $tmp[$examples[$i +
1]] = $examples[$i];
198 foreach ( $examples as $k => $v ) {
199 if ( is_numeric( $k ) ) {
204 $msg = self
::escapeWikiText( $v );
205 if ( is_array( $msg ) ) {
206 $msg = join( " ", $msg );
210 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
211 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
219 * Return links to more detailed help pages about the module.
220 * @since 1.25, returning boolean false is deprecated
221 * @return string|array
223 public function getHelpUrls() {
228 * Returns an array of allowed parameters (parameter name) => (default
229 * value) or (parameter name) => (array with PARAM_* constants as keys)
230 * Don't call this function directly: use getFinalParams() to allow
231 * hooks to modify parameters as needed.
233 * Some derived classes may choose to handle an integer $flags parameter
234 * in the overriding methods. Callers of this method can pass zero or
235 * more OR-ed flags like GET_VALUES_FOR_HELP.
239 protected function getAllowedParams( /* $flags = 0 */ ) {
240 // int $flags is not declared because it causes "Strict standards"
241 // warning. Most derived classes do not implement it.
246 * Indicates if this module needs maxlag to be checked
249 public function shouldCheckMaxlag() {
254 * Indicates whether this module requires read rights
257 public function isReadMode() {
262 * Indicates whether this module requires write mode
265 public function isWriteMode() {
270 * Indicates whether this module must be called with a POST request
273 public function mustBePosted() {
274 return $this->needsToken() !== false;
278 * Indicates whether this module is deprecated
282 public function isDeprecated() {
287 * Indicates whether this module is "internal"
288 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
292 public function isInternal() {
297 * Returns the token type this module requires in order to execute.
299 * Modules are strongly encouraged to use the core 'csrf' type unless they
300 * have specialized security needs. If the token type is not one of the
301 * core types, you must use the ApiQueryTokensRegisterTypes hook to
304 * Returning a non-falsey value here will force the addition of an
305 * appropriate 'token' parameter in self::getFinalParams(). Also,
306 * self::mustBePosted() must return true when tokens are used.
308 * In previous versions of MediaWiki, true was a valid return value.
309 * Returning true will generate errors indicating that the API module needs
312 * @return string|false
314 public function needsToken() {
319 * Fetch the salt used in the Web UI corresponding to this module.
321 * Only override this if the Web UI uses a token with a non-constant salt.
324 * @param array $params All supplied parameters for the module
325 * @return string|array|null
327 protected function getWebUITokenSalt( array $params ) {
333 /************************************************************************//**
334 * @name Data access methods
339 * Get the name of the module being executed by this instance
342 public function getModuleName() {
343 return $this->mModuleName
;
347 * Get parameter prefix (usually two letters or an empty string).
350 public function getModulePrefix() {
351 return $this->mModulePrefix
;
355 * Get the main module
358 public function getMain() {
359 return $this->mMainModule
;
363 * Returns true if this module is the main module ($this === $this->mMainModule),
367 public function isMain() {
368 return $this === $this->mMainModule
;
372 * Get the parent of this module
374 * @return ApiBase|null
376 public function getParent() {
377 return $this->isMain() ?
null : $this->getMain();
381 * Get the path to this module
386 public function getModulePath() {
387 if ( $this->isMain() ) {
389 } elseif ( $this->getParent()->isMain() ) {
390 return $this->getModuleName();
392 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
397 * Get a module from its module path
400 * @param string $path
401 * @return ApiBase|null
402 * @throws UsageException
404 public function getModuleFromPath( $path ) {
405 $module = $this->getMain();
406 if ( $path === 'main' ) {
410 $parts = explode( '+', $path );
411 if ( count( $parts ) === 1 ) {
412 // In case the '+' was typed into URL, it resolves as a space
413 $parts = explode( ' ', $path );
416 $count = count( $parts );
417 for ( $i = 0; $i < $count; $i++
) {
419 $manager = $parent->getModuleManager();
420 if ( $manager === null ) {
421 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
422 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
424 $module = $manager->getModule( $parts[$i] );
426 if ( $module === null ) {
427 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
429 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
439 * Get the result object
442 public function getResult() {
443 // Main module has getResult() method overridden
444 // Safety - avoid infinite loop:
445 if ( $this->isMain() ) {
446 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
449 return $this->getMain()->getResult();
453 * Get the result data array (read-only)
456 public function getResultData() {
457 return $this->getResult()->getData();
461 * Gets a default slave database connection object
462 * @return DatabaseBase
464 protected function getDB() {
465 if ( !isset( $this->mSlaveDB
) ) {
466 $this->profileDBIn();
467 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
468 $this->profileDBOut();
471 return $this->mSlaveDB
;
476 /************************************************************************//**
477 * @name Parameter handling
482 * This method mangles parameter name based on the prefix supplied to the constructor.
483 * Override this method to change parameter name during runtime
484 * @param string $paramName Parameter name
485 * @return string Prefixed parameter name
487 public function encodeParamName( $paramName ) {
488 return $this->mModulePrefix
. $paramName;
492 * Using getAllowedParams(), this function makes an array of the values
493 * provided by the user, with key being the name of the variable, and
494 * value - validated value from user or default. limits will not be
495 * parsed if $parseLimit is set to false; use this when the max
496 * limit is not definitive yet, e.g. when getting revisions.
497 * @param bool $parseLimit True by default
500 public function extractRequestParams( $parseLimit = true ) {
501 // Cache parameters, for performance and to avoid bug 24564.
502 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
503 $params = $this->getFinalParams();
506 if ( $params ) { // getFinalParams() can return false
507 foreach ( $params as $paramName => $paramSettings ) {
508 $results[$paramName] = $this->getParameterFromSettings(
509 $paramName, $paramSettings, $parseLimit );
512 $this->mParamCache
[$parseLimit] = $results;
515 return $this->mParamCache
[$parseLimit];
519 * Get a value for the given parameter
520 * @param string $paramName Parameter name
521 * @param bool $parseLimit See extractRequestParams()
522 * @return mixed Parameter value
524 protected function getParameter( $paramName, $parseLimit = true ) {
525 $params = $this->getFinalParams();
526 $paramSettings = $params[$paramName];
528 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
532 * Die if none or more than one of a certain set of parameters is set and not false.
534 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
535 * @param string $required,... Names of parameters of which exactly one must be set
537 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
538 $required = func_get_args();
539 array_shift( $required );
540 $p = $this->getModulePrefix();
542 $intersection = array_intersect( array_keys( array_filter( $params,
543 array( $this, "parameterNotEmpty" ) ) ), $required );
545 if ( count( $intersection ) > 1 ) {
547 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
549 } elseif ( count( $intersection ) == 0 ) {
551 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
558 * Die if more than one of a certain set of parameters is set and not false.
560 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
561 * @param string $required,... Names of parameters of which at most one must be set
563 public function requireMaxOneParameter( $params, $required /*...*/ ) {
564 $required = func_get_args();
565 array_shift( $required );
566 $p = $this->getModulePrefix();
568 $intersection = array_intersect( array_keys( array_filter( $params,
569 array( $this, "parameterNotEmpty" ) ) ), $required );
571 if ( count( $intersection ) > 1 ) {
573 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
580 * Die if none of a certain set of parameters is set and not false.
583 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
584 * @param string $required,... Names of parameters of which at least one must be set
586 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
587 $required = func_get_args();
588 array_shift( $required );
589 $p = $this->getModulePrefix();
591 $intersection = array_intersect(
592 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
596 if ( count( $intersection ) == 0 ) {
597 $this->dieUsage( "At least one of the parameters {$p}" .
598 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
603 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
605 * @param object $x Parameter to check is not null/false
608 private function parameterNotEmpty( $x ) {
609 return !is_null( $x ) && $x !== false;
613 * Get a WikiPage object from a title or pageid param, if possible.
614 * Can die, if no param is set or if the title or page id is not valid.
616 * @param array $params
617 * @param bool|string $load Whether load the object's state from the database:
618 * - false: don't load (if the pageid is given, it will still be loaded)
619 * - 'fromdb': load from a slave database
620 * - 'fromdbmaster': load from the master database
623 public function getTitleOrPageId( $params, $load = false ) {
624 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
627 if ( isset( $params['title'] ) ) {
628 $titleObj = Title
::newFromText( $params['title'] );
629 if ( !$titleObj ||
$titleObj->isExternal() ) {
630 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
632 if ( !$titleObj->canExist() ) {
633 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
635 $pageObj = WikiPage
::factory( $titleObj );
636 if ( $load !== false ) {
637 $pageObj->loadPageData( $load );
639 } elseif ( isset( $params['pageid'] ) ) {
640 if ( $load === false ) {
643 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
645 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
653 * Return true if we're to watch the page, false if not, null if no change.
654 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
655 * @param Title $titleObj The page under consideration
656 * @param string $userOption The user option to consider when $watchlist=preferences.
657 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
660 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
662 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
664 switch ( $watchlist ) {
672 # If the user is already watching, don't bother checking
673 if ( $userWatching ) {
676 # If no user option was passed, use watchdefault and watchcreations
677 if ( is_null( $userOption ) ) {
678 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
679 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
682 # Watch the article based on the user preference
683 return $this->getUser()->getBoolOption( $userOption );
686 return $userWatching;
689 return $userWatching;
694 * Using the settings determine the value for the given parameter
696 * @param string $paramName Parameter name
697 * @param array|mixed $paramSettings Default value or an array of settings
698 * using PARAM_* constants.
699 * @param bool $parseLimit Parse limit?
700 * @return mixed Parameter value
702 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
703 // Some classes may decide to change parameter names
704 $encParamName = $this->encodeParamName( $paramName );
706 if ( !is_array( $paramSettings ) ) {
707 $default = $paramSettings;
709 $type = gettype( $paramSettings );
714 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
715 ?
$paramSettings[self
::PARAM_DFLT
]
717 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
718 ?
$paramSettings[self
::PARAM_ISMULTI
]
720 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
721 ?
$paramSettings[self
::PARAM_TYPE
]
723 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
724 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
726 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
727 ?
$paramSettings[self
::PARAM_DEPRECATED
]
729 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
730 ?
$paramSettings[self
::PARAM_REQUIRED
]
733 // When type is not given, and no choices, the type is the same as $default
734 if ( !isset( $type ) ) {
735 if ( isset( $default ) ) {
736 $type = gettype( $default );
738 $type = 'NULL'; // allow everything
743 if ( $type == 'boolean' ) {
744 if ( isset( $default ) && $default !== false ) {
745 // Having a default value of anything other than 'false' is not allowed
748 "Boolean param $encParamName's default is set to '$default'. " .
749 "Boolean parameters must default to false."
753 $value = $this->getMain()->getCheck( $encParamName );
754 } elseif ( $type == 'upload' ) {
755 if ( isset( $default ) ) {
756 // Having a default value is not allowed
759 "File upload param $encParamName's default is set to " .
760 "'$default'. File upload parameters may not have a default." );
763 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
765 $value = $this->getMain()->getUpload( $encParamName );
766 if ( !$value->exists() ) {
767 // This will get the value without trying to normalize it
768 // (because trying to normalize a large binary file
769 // accidentally uploaded as a field fails spectacularly)
770 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
771 if ( $value !== null ) {
773 "File upload param $encParamName is not a file upload; " .
774 "be sure to use multipart/form-data for your POST and include " .
775 "a filename in the Content-Disposition header.",
776 "badupload_{$encParamName}"
781 $value = $this->getMain()->getVal( $encParamName, $default );
783 if ( isset( $value ) && $type == 'namespace' ) {
784 $type = MWNamespace
::getValidNamespaces();
786 if ( isset( $value ) && $type == 'submodule' ) {
787 $type = $this->getModuleManager()->getNames( $paramName );
791 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
792 $value = $this->parseMultiValue(
796 is_array( $type ) ?
$type : null
800 // More validation only when choices were not given
801 // choices were validated in parseMultiValue()
802 if ( isset( $value ) ) {
803 if ( !is_array( $type ) ) {
805 case 'NULL': // nothing to do
808 if ( $required && $value === '' ) {
809 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
812 case 'integer': // Force everything using intval() and optionally validate limits
813 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
814 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
815 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
816 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
818 if ( is_array( $value ) ) {
819 $value = array_map( 'intval', $value );
820 if ( !is_null( $min ) ||
!is_null( $max ) ) {
821 foreach ( $value as &$v ) {
822 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
826 $value = intval( $value );
827 if ( !is_null( $min ) ||
!is_null( $max ) ) {
828 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
833 if ( !$parseLimit ) {
834 // Don't do any validation whatsoever
837 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
838 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
842 "MAX1 or MAX2 are not defined for the limit $encParamName"
846 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
848 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
849 if ( $value == 'max' ) {
850 $value = $this->getMain()->canApiHighLimits()
851 ?
$paramSettings[self
::PARAM_MAX2
]
852 : $paramSettings[self
::PARAM_MAX
];
853 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
855 $value = intval( $value );
856 $this->validateLimit(
860 $paramSettings[self
::PARAM_MAX
],
861 $paramSettings[self
::PARAM_MAX2
]
867 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
871 if ( is_array( $value ) ) {
872 foreach ( $value as $key => $val ) {
873 $value[$key] = $this->validateTimestamp( $val, $encParamName );
876 $value = $this->validateTimestamp( $value, $encParamName );
880 if ( is_array( $value ) ) {
881 foreach ( $value as $key => $val ) {
882 $value[$key] = $this->validateUser( $val, $encParamName );
885 $value = $this->validateUser( $value, $encParamName );
888 case 'upload': // nothing to do
891 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
895 // Throw out duplicates if requested
896 if ( !$dupes && is_array( $value ) ) {
897 $value = array_unique( $value );
900 // Set a warning if a deprecated parameter has been passed
901 if ( $deprecated && $value !== false ) {
902 $this->setWarning( "The $encParamName parameter has been deprecated." );
904 } elseif ( $required ) {
905 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
912 * Return an array of values that were given in a 'a|b|c' notation,
913 * after it optionally validates them against the list allowed values.
915 * @param string $valueName The name of the parameter (for error
917 * @param mixed $value The value being parsed
918 * @param bool $allowMultiple Can $value contain more than one value
920 * @param string[]|null $allowedValues An array of values to check against. If
921 * null, all values are accepted.
922 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
924 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
925 if ( trim( $value ) === '' && $allowMultiple ) {
929 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
930 // because it unstubs $wgUser
931 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
932 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
936 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
937 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
938 "the limit is $sizeLimit" );
941 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
942 // Bug 33482 - Allow entries with | in them for non-multiple values
943 if ( in_array( $value, $allowedValues, true ) ) {
947 $possibleValues = is_array( $allowedValues )
948 ?
"of '" . implode( "', '", $allowedValues ) . "'"
951 "Only one $possibleValues is allowed for parameter '$valueName'",
952 "multival_$valueName"
956 if ( is_array( $allowedValues ) ) {
957 // Check for unknown values
958 $unknown = array_diff( $valuesList, $allowedValues );
959 if ( count( $unknown ) ) {
960 if ( $allowMultiple ) {
961 $s = count( $unknown ) > 1 ?
's' : '';
962 $vals = implode( ", ", $unknown );
963 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
966 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
971 // Now throw them out
972 $valuesList = array_intersect( $valuesList, $allowedValues );
975 return $allowMultiple ?
$valuesList : $valuesList[0];
979 * Validate the value against the minimum and user/bot maximum limits.
980 * Prints usage info on failure.
981 * @param string $paramName Parameter name
982 * @param int $value Parameter value
983 * @param int|null $min Minimum value
984 * @param int|null $max Maximum value for users
985 * @param int $botMax Maximum value for sysops/bots
986 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
988 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
989 if ( !is_null( $min ) && $value < $min ) {
991 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
992 $this->warnOrDie( $msg, $enforceLimits );
996 // Minimum is always validated, whereas maximum is checked only if not
997 // running in internal call mode
998 if ( $this->getMain()->isInternalMode() ) {
1002 // Optimization: do not check user's bot status unless really needed -- skips db query
1003 // assumes $botMax >= $max
1004 if ( !is_null( $max ) && $value > $max ) {
1005 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1006 if ( $value > $botMax ) {
1007 $msg = $this->encodeParamName( $paramName ) .
1008 " may not be over $botMax (set to $value) for bots or sysops";
1009 $this->warnOrDie( $msg, $enforceLimits );
1013 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1014 $this->warnOrDie( $msg, $enforceLimits );
1021 * Validate and normalize of parameters of type 'timestamp'
1022 * @param string $value Parameter value
1023 * @param string $encParamName Parameter name
1024 * @return string Validated and normalized parameter
1026 protected function validateTimestamp( $value, $encParamName ) {
1027 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1028 if ( $unixTimestamp === false ) {
1030 "Invalid value '$value' for timestamp parameter $encParamName",
1031 "badtimestamp_{$encParamName}"
1035 return wfTimestamp( TS_MW
, $unixTimestamp );
1039 * Validate the supplied token.
1042 * @param string $token Supplied token
1043 * @param array $params All supplied parameters for the module
1046 final public function validateToken( $token, array $params ) {
1047 $tokenType = $this->needsToken();
1048 $salts = ApiQueryTokens
::getTokenTypeSalts();
1049 if ( !isset( $salts[$tokenType] ) ) {
1050 throw new MWException(
1051 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1052 'without registering it'
1056 if ( $this->getUser()->matchEditToken(
1064 $webUiSalt = $this->getWebUITokenSalt( $params );
1065 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1077 * Validate and normalize of parameters of type 'user'
1078 * @param string $value Parameter value
1079 * @param string $encParamName Parameter name
1080 * @return string Validated and normalized parameter
1082 private function validateUser( $value, $encParamName ) {
1083 $title = Title
::makeTitleSafe( NS_USER
, $value );
1084 if ( $title === null ) {
1086 "Invalid value '$value' for user parameter $encParamName",
1087 "baduser_{$encParamName}"
1091 return $title->getText();
1096 /************************************************************************//**
1097 * @name Utility methods
1102 * Set a watch (or unwatch) based the based on a watchlist parameter.
1103 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1104 * @param Title $titleObj The article's title to change
1105 * @param string $userOption The user option to consider when $watch=preferences
1107 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1108 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1109 if ( $value === null ) {
1113 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1117 * Truncate an array to a certain length.
1118 * @param array $arr Array to truncate
1119 * @param int $limit Maximum length
1120 * @return bool True if the array was truncated, false otherwise
1122 public static function truncateArray( &$arr, $limit ) {
1124 while ( count( $arr ) > $limit ) {
1133 * Gets the user for whom to get the watchlist
1135 * @param array $params
1138 public function getWatchlistUser( $params ) {
1139 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1140 $user = User
::newFromName( $params['owner'], false );
1141 if ( !( $user && $user->getId() ) ) {
1142 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1144 $token = $user->getOption( 'watchlisttoken' );
1145 if ( $token == '' ||
$token != $params['token'] ) {
1147 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1152 if ( !$this->getUser()->isLoggedIn() ) {
1153 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1155 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1156 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1158 $user = $this->getUser();
1165 * A subset of wfEscapeWikiText for BC texts
1168 * @param string|array $v
1169 * @return string|array
1171 private static function escapeWikiText( $v ) {
1172 if ( is_array( $v ) ) {
1173 return array_map( 'self::escapeWikiText', $v );
1175 return strtr( $v, array(
1176 '__' => '__', '{' => '{', '}' => '}',
1177 '[[Category:' => '[[:Category:',
1178 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1184 * Create a Message from a string or array
1186 * A string is used as a message key. An array has the message key as the
1187 * first value and message parameters as subsequent values.
1190 * @param string|array|Message $msg
1191 * @param IContextSource $context
1192 * @param array $params
1193 * @return Message|null
1195 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1196 if ( is_string( $msg ) ) {
1197 $msg = wfMessage( $msg );
1198 } elseif ( is_array( $msg ) ) {
1199 $msg = call_user_func_array( 'wfMessage', $msg );
1201 if ( !$msg instanceof Message
) {
1205 $msg->setContext( $context );
1207 $msg->params( $params );
1215 /************************************************************************//**
1216 * @name Warning and error reporting
1221 * Set warning section for this module. Users should monitor this
1222 * section to notice any changes in API. Multiple calls to this
1223 * function will result in the warning messages being separated by
1225 * @param string $warning Warning message
1227 public function setWarning( $warning ) {
1228 $result = $this->getResult();
1229 $data = $result->getData();
1230 $moduleName = $this->getModuleName();
1231 if ( isset( $data['warnings'][$moduleName] ) ) {
1232 // Don't add duplicate warnings
1233 $oldWarning = $data['warnings'][$moduleName]['*'];
1234 $warnPos = strpos( $oldWarning, $warning );
1235 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1236 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1237 // Check if $warning is followed by "\n" or the end of the $oldWarning
1238 $warnPos +
= strlen( $warning );
1239 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1243 // If there is a warning already, append it to the existing one
1244 $warning = "$oldWarning\n$warning";
1247 ApiResult
::setContent( $msg, $warning );
1248 $result->addValue( 'warnings', $moduleName,
1249 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1253 * Adds a warning to the output, else dies
1255 * @param string $msg Message to show as a warning, or error message if dying
1256 * @param bool $enforceLimits Whether this is an enforce (die)
1258 private function warnOrDie( $msg, $enforceLimits = false ) {
1259 if ( $enforceLimits ) {
1260 $this->dieUsage( $msg, 'integeroutofrange' );
1263 $this->setWarning( $msg );
1267 * Throw a UsageException, which will (if uncaught) call the main module's
1268 * error handler and die with an error message.
1270 * @param string $description One-line human-readable description of the
1271 * error condition, e.g., "The API requires a valid action parameter"
1272 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1273 * automated identification of the error, e.g., 'unknown_action'
1274 * @param int $httpRespCode HTTP response code
1275 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1276 * @throws UsageException
1278 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1279 Profiler
::instance()->close();
1280 throw new UsageException(
1282 $this->encodeParamName( $errorCode ),
1289 * Get error (as code, string) from a Status object.
1292 * @param Status $status
1293 * @return array Array of code and error string
1295 public function getErrorFromStatus( $status ) {
1296 if ( $status->isGood() ) {
1297 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1300 $errors = $status->getErrorsArray();
1302 // No errors? Assume the warnings should be treated as errors
1303 $errors = $status->getWarningsArray();
1306 // Still no errors? Punt
1307 $errors = array( array( 'unknownerror-nocode' ) );
1310 // Cannot use dieUsageMsg() because extensions might return custom
1312 if ( $errors[0] instanceof Message
) {
1314 $code = $msg->getKey();
1316 $code = array_shift( $errors[0] );
1317 $msg = wfMessage( $code, $errors[0] );
1319 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1320 // Translate message to code, for backwards compatibility
1321 $code = ApiBase
::$messageMap[$code]['code'];
1324 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1328 * Throw a UsageException based on the errors in the Status object.
1331 * @param Status $status
1332 * @throws MWException
1334 public function dieStatus( $status ) {
1336 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1337 $this->dieUsage( $msg, $code );
1340 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1342 * Array that maps message keys to error messages. $1 and friends are replaced.
1344 public static $messageMap = array(
1345 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1346 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1347 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1349 // Messages from Title::getUserPermissionsErrors()
1350 'ns-specialprotected' => array(
1351 'code' => 'unsupportednamespace',
1352 'info' => "Pages in the Special namespace can't be edited"
1354 'protectedinterface' => array(
1355 'code' => 'protectednamespace-interface',
1356 'info' => "You're not allowed to edit interface messages"
1358 'namespaceprotected' => array(
1359 'code' => 'protectednamespace',
1360 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1362 'customcssprotected' => array(
1363 'code' => 'customcssprotected',
1364 'info' => "You're not allowed to edit custom CSS pages"
1366 'customjsprotected' => array(
1367 'code' => 'customjsprotected',
1368 'info' => "You're not allowed to edit custom JavaScript pages"
1370 'cascadeprotected' => array(
1371 'code' => 'cascadeprotected',
1372 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1374 'protectedpagetext' => array(
1375 'code' => 'protectedpage',
1376 'info' => "The \"\$1\" right is required to edit this page"
1378 'protect-cantedit' => array(
1379 'code' => 'cantedit',
1380 'info' => "You can't protect this page because you can't edit it"
1382 'deleteprotected' => array(
1383 'code' => 'cantedit',
1384 'info' => "You can't delete this page because it has been protected"
1386 'badaccess-group0' => array(
1387 'code' => 'permissiondenied',
1388 'info' => "Permission denied"
1389 ), // Generic permission denied message
1390 'badaccess-groups' => array(
1391 'code' => 'permissiondenied',
1392 'info' => "Permission denied"
1394 'titleprotected' => array(
1395 'code' => 'protectedtitle',
1396 'info' => "This title has been protected from creation"
1398 'nocreate-loggedin' => array(
1399 'code' => 'cantcreate',
1400 'info' => "You don't have permission to create new pages"
1402 'nocreatetext' => array(
1403 'code' => 'cantcreate-anon',
1404 'info' => "Anonymous users can't create new pages"
1406 'movenologintext' => array(
1407 'code' => 'cantmove-anon',
1408 'info' => "Anonymous users can't move pages"
1410 'movenotallowed' => array(
1411 'code' => 'cantmove',
1412 'info' => "You don't have permission to move pages"
1414 'confirmedittext' => array(
1415 'code' => 'confirmemail',
1416 'info' => "You must confirm your email address before you can edit"
1418 'blockedtext' => array(
1419 'code' => 'blocked',
1420 'info' => "You have been blocked from editing"
1422 'autoblockedtext' => array(
1423 'code' => 'autoblocked',
1424 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1427 // Miscellaneous interface messages
1428 'actionthrottledtext' => array(
1429 'code' => 'ratelimited',
1430 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1432 'alreadyrolled' => array(
1433 'code' => 'alreadyrolled',
1434 'info' => "The page you tried to rollback was already rolled back"
1436 'cantrollback' => array(
1437 'code' => 'onlyauthor',
1438 'info' => "The page you tried to rollback only has one author"
1440 'readonlytext' => array(
1441 'code' => 'readonly',
1442 'info' => "The wiki is currently in read-only mode"
1444 'sessionfailure' => array(
1445 'code' => 'badtoken',
1446 'info' => "Invalid token" ),
1447 'cannotdelete' => array(
1448 'code' => 'cantdelete',
1449 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1451 'notanarticle' => array(
1452 'code' => 'missingtitle',
1453 'info' => "The page you requested doesn't exist"
1455 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1457 'immobile_namespace' => array(
1458 'code' => 'immobilenamespace',
1459 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1461 'articleexists' => array(
1462 'code' => 'articleexists',
1463 'info' => "The destination article already exists and is not a redirect to the source article"
1465 'protectedpage' => array(
1466 'code' => 'protectedpage',
1467 'info' => "You don't have permission to perform this move"
1469 'hookaborted' => array(
1470 'code' => 'hookaborted',
1471 'info' => "The modification you tried to make was aborted by an extension hook"
1473 'cantmove-titleprotected' => array(
1474 'code' => 'protectedtitle',
1475 'info' => "The destination article has been protected from creation"
1477 'imagenocrossnamespace' => array(
1478 'code' => 'nonfilenamespace',
1479 'info' => "Can't move a file to a non-file namespace"
1481 'imagetypemismatch' => array(
1482 'code' => 'filetypemismatch',
1483 'info' => "The new file extension doesn't match its type"
1485 // 'badarticleerror' => shouldn't happen
1486 // 'badtitletext' => shouldn't happen
1487 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1488 'range_block_disabled' => array(
1489 'code' => 'rangedisabled',
1490 'info' => "Blocking IP ranges has been disabled"
1492 'nosuchusershort' => array(
1493 'code' => 'nosuchuser',
1494 'info' => "The user you specified doesn't exist"
1496 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1497 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1498 'ipb_already_blocked' => array(
1499 'code' => 'alreadyblocked',
1500 'info' => "The user you tried to block was already blocked"
1502 'ipb_blocked_as_range' => array(
1503 'code' => 'blockedasrange',
1504 '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."
1506 'ipb_cant_unblock' => array(
1507 'code' => 'cantunblock',
1508 'info' => "The block you specified was not found. It may have been unblocked already"
1510 'mailnologin' => array(
1511 'code' => 'cantsend',
1512 '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"
1514 'ipbblocked' => array(
1515 'code' => 'ipbblocked',
1516 'info' => 'You cannot block or unblock users while you are yourself blocked'
1518 'ipbnounblockself' => array(
1519 'code' => 'ipbnounblockself',
1520 'info' => 'You are not allowed to unblock yourself'
1522 'usermaildisabled' => array(
1523 'code' => 'usermaildisabled',
1524 'info' => "User email has been disabled"
1526 'blockedemailuser' => array(
1527 'code' => 'blockedfrommail',
1528 'info' => "You have been blocked from sending email"
1530 'notarget' => array(
1531 'code' => 'notarget',
1532 'info' => "You have not specified a valid target for this action"
1535 'code' => 'noemail',
1536 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1538 'rcpatroldisabled' => array(
1539 'code' => 'patroldisabled',
1540 'info' => "Patrolling is disabled on this wiki"
1542 'markedaspatrollederror-noautopatrol' => array(
1543 'code' => 'noautopatrol',
1544 'info' => "You don't have permission to patrol your own changes"
1546 'delete-toobig' => array(
1547 'code' => 'bigdelete',
1548 'info' => "You can't delete this page because it has more than \$1 revisions"
1550 'movenotallowedfile' => array(
1551 'code' => 'cantmovefile',
1552 'info' => "You don't have permission to move files"
1554 'userrights-no-interwiki' => array(
1555 'code' => 'nointerwikiuserrights',
1556 'info' => "You don't have permission to change user rights on other wikis"
1558 'userrights-nodatabase' => array(
1559 'code' => 'nosuchdatabase',
1560 'info' => "Database \"\$1\" does not exist or is not local"
1562 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1563 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1564 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1565 'import-rootpage-invalid' => array(
1566 'code' => 'import-rootpage-invalid',
1567 'info' => 'Root page is an invalid title'
1569 'import-rootpage-nosubpage' => array(
1570 'code' => 'import-rootpage-nosubpage',
1571 'info' => 'Namespace "$1" of the root page does not allow subpages'
1574 // API-specific messages
1575 'readrequired' => array(
1576 'code' => 'readapidenied',
1577 'info' => "You need read permission to use this module"
1579 'writedisabled' => array(
1580 'code' => 'noapiwrite',
1581 '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"
1583 'writerequired' => array(
1584 'code' => 'writeapidenied',
1585 'info' => "You're not allowed to edit this wiki through the API"
1587 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1588 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1589 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1590 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1591 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1592 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1593 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1594 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1595 'create-titleexists' => array(
1596 'code' => 'create-titleexists',
1597 'info' => "Existing titles can't be protected with 'create'"
1599 'missingtitle-createonly' => array(
1600 'code' => 'missingtitle-createonly',
1601 'info' => "Missing titles can only be protected with 'create'"
1603 'cantblock' => array( 'code' => 'cantblock',
1604 'info' => "You don't have permission to block users"
1606 'canthide' => array(
1607 'code' => 'canthide',
1608 'info' => "You don't have permission to hide user names from the block log"
1610 'cantblock-email' => array(
1611 'code' => 'cantblock-email',
1612 'info' => "You don't have permission to block users from sending email through the wiki"
1614 'unblock-notarget' => array(
1615 'code' => 'notarget',
1616 'info' => "Either the id or the user parameter must be set"
1618 'unblock-idanduser' => array(
1619 'code' => 'idanduser',
1620 'info' => "The id and user parameters can't be used together"
1622 'cantunblock' => array(
1623 'code' => 'permissiondenied',
1624 'info' => "You don't have permission to unblock users"
1626 'cannotundelete' => array(
1627 'code' => 'cantundelete',
1628 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1630 'permdenied-undelete' => array(
1631 'code' => 'permissiondenied',
1632 'info' => "You don't have permission to restore deleted revisions"
1634 'createonly-exists' => array(
1635 'code' => 'articleexists',
1636 'info' => "The article you tried to create has been created already"
1638 'nocreate-missing' => array(
1639 'code' => 'missingtitle',
1640 'info' => "The article you tried to edit doesn't exist"
1642 'cantchangecontentmodel' => array(
1643 'code' => 'cantchangecontentmodel',
1644 'info' => "You don't have permission to change the content model of a page"
1646 'nosuchrcid' => array(
1647 'code' => 'nosuchrcid',
1648 'info' => "There is no change with rcid \"\$1\""
1650 'protect-invalidaction' => array(
1651 'code' => 'protect-invalidaction',
1652 'info' => "Invalid protection type \"\$1\""
1654 'protect-invalidlevel' => array(
1655 'code' => 'protect-invalidlevel',
1656 'info' => "Invalid protection level \"\$1\""
1658 'toofewexpiries' => array(
1659 'code' => 'toofewexpiries',
1660 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1662 'cantimport' => array(
1663 'code' => 'cantimport',
1664 'info' => "You don't have permission to import pages"
1666 'cantimport-upload' => array(
1667 'code' => 'cantimport-upload',
1668 'info' => "You don't have permission to import uploaded pages"
1670 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1671 'importuploaderrorsize' => array(
1672 'code' => 'filetoobig',
1673 'info' => 'The file you uploaded is bigger than the maximum upload size'
1675 'importuploaderrorpartial' => array(
1676 'code' => 'partialupload',
1677 'info' => 'The file was only partially uploaded'
1679 'importuploaderrortemp' => array(
1680 'code' => 'notempdir',
1681 'info' => 'The temporary upload directory is missing'
1683 'importcantopen' => array(
1684 'code' => 'cantopenfile',
1685 'info' => "Couldn't open the uploaded file"
1687 'import-noarticle' => array(
1688 'code' => 'badinterwiki',
1689 'info' => 'Invalid interwiki title specified'
1691 'importbadinterwiki' => array(
1692 'code' => 'badinterwiki',
1693 'info' => 'Invalid interwiki title specified'
1695 'import-unknownerror' => array(
1696 'code' => 'import-unknownerror',
1697 'info' => "Unknown error on import: \"\$1\""
1699 'cantoverwrite-sharedfile' => array(
1700 'code' => 'cantoverwrite-sharedfile',
1701 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1703 'sharedfile-exists' => array(
1704 'code' => 'fileexists-sharedrepo-perm',
1705 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1707 'mustbeposted' => array(
1708 'code' => 'mustbeposted',
1709 'info' => "The \$1 module requires a POST request"
1713 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1715 'specialpage-cantexecute' => array(
1716 'code' => 'specialpage-cantexecute',
1717 'info' => "You don't have permission to view the results of this special page"
1719 'invalidoldimage' => array(
1720 'code' => 'invalidoldimage',
1721 'info' => 'The oldimage parameter has invalid format'
1723 'nodeleteablefile' => array(
1724 'code' => 'nodeleteablefile',
1725 'info' => 'No such old version of the file'
1727 'fileexists-forbidden' => array(
1728 'code' => 'fileexists-forbidden',
1729 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1731 'fileexists-shared-forbidden' => array(
1732 'code' => 'fileexists-shared-forbidden',
1733 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1735 'filerevert-badversion' => array(
1736 'code' => 'filerevert-badversion',
1737 'info' => 'There is no previous local version of this file with the provided timestamp.'
1740 // ApiEditPage messages
1741 'noimageredirect-anon' => array(
1742 'code' => 'noimageredirect-anon',
1743 'info' => "Anonymous users can't create image redirects"
1745 'noimageredirect-logged' => array(
1746 'code' => 'noimageredirect',
1747 'info' => "You don't have permission to create image redirects"
1749 'spamdetected' => array(
1750 'code' => 'spamdetected',
1751 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1753 'contenttoobig' => array(
1754 'code' => 'contenttoobig',
1755 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1757 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1758 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1759 'wasdeleted' => array(
1760 'code' => 'pagedeleted',
1761 'info' => "The page has been deleted since you fetched its timestamp"
1763 'blankpage' => array(
1764 'code' => 'emptypage',
1765 'info' => "Creating new, empty pages is not allowed"
1767 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1768 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1769 'missingtext' => array(
1771 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1773 'emptynewsection' => array(
1774 'code' => 'emptynewsection',
1775 'info' => 'Creating empty new sections is not possible.'
1777 'revwrongpage' => array(
1778 'code' => 'revwrongpage',
1779 'info' => "r\$1 is not a revision of \"\$2\""
1781 'undo-failure' => array(
1782 'code' => 'undofailure',
1783 'info' => 'Undo failed due to conflicting intermediate edits'
1785 'content-not-allowed-here' => array(
1786 'code' => 'contentnotallowedhere',
1787 'info' => 'Content model "$1" is not allowed at title "$2"'
1790 // Messages from WikiPage::doEit()
1791 'edit-hook-aborted' => array(
1792 'code' => 'edit-hook-aborted',
1793 'info' => "Your edit was aborted by an ArticleSave hook"
1795 'edit-gone-missing' => array(
1796 'code' => 'edit-gone-missing',
1797 'info' => "The page you tried to edit doesn't seem to exist anymore"
1799 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1800 'edit-already-exists' => array(
1801 'code' => 'edit-already-exists',
1802 'info' => 'It seems the page you tried to create already exist'
1806 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1807 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1808 'uploaddisabled' => array(
1809 'code' => 'uploaddisabled',
1810 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1812 'copyuploaddisabled' => array(
1813 'code' => 'copyuploaddisabled',
1814 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1816 'copyuploadbaddomain' => array(
1817 'code' => 'copyuploadbaddomain',
1818 'info' => 'Uploads by URL are not allowed from this domain.'
1820 'copyuploadbadurl' => array(
1821 'code' => 'copyuploadbadurl',
1822 'info' => 'Upload not allowed from this URL.'
1825 'filename-tooshort' => array(
1826 'code' => 'filename-tooshort',
1827 'info' => 'The filename is too short'
1829 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1830 'illegal-filename' => array(
1831 'code' => 'illegal-filename',
1832 'info' => 'The filename is not allowed'
1834 'filetype-missing' => array(
1835 'code' => 'filetype-missing',
1836 'info' => 'The file is missing an extension'
1839 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1841 // @codingStandardsIgnoreEnd
1844 * Helper function for readonly errors
1846 public function dieReadOnly() {
1847 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1848 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1849 array( 'readonlyreason' => wfReadOnlyReason() ) );
1853 * Output the error message related to a certain array
1854 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1856 public function dieUsageMsg( $error ) {
1857 # most of the time we send a 1 element, so we might as well send it as
1858 # a string and make this an array here.
1859 if ( is_string( $error ) ) {
1860 $error = array( $error );
1862 $parsed = $this->parseMsg( $error );
1863 $this->dieUsage( $parsed['info'], $parsed['code'] );
1867 * Will only set a warning instead of failing if the global $wgDebugAPI
1868 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1869 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1872 public function dieUsageMsgOrDebug( $error ) {
1873 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1874 $this->dieUsageMsg( $error );
1877 if ( is_string( $error ) ) {
1878 $error = array( $error );
1880 $parsed = $this->parseMsg( $error );
1881 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1885 * Die with the $prefix.'badcontinue' error. This call is common enough to
1886 * make it into the base method.
1887 * @param bool $condition Will only die if this value is true
1890 protected function dieContinueUsageIf( $condition ) {
1893 'Invalid continue param. You should pass the original value returned by the previous query',
1899 * Return the error message related to a certain array
1900 * @param array $error Element of a getUserPermissionsErrors()-style array
1901 * @return array('code' => code, 'info' => info)
1903 public function parseMsg( $error ) {
1904 $error = (array)$error; // It seems strings sometimes make their way in here
1905 $key = array_shift( $error );
1907 // Check whether the error array was nested
1908 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1909 if ( is_array( $key ) ) {
1911 $key = array_shift( $error );
1914 if ( isset( self
::$messageMap[$key] ) ) {
1916 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1917 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1921 // If the key isn't present, throw an "unknown error"
1922 return $this->parseMsg( array( 'unknownerror', $key ) );
1926 * Internal code errors should be reported with this method
1927 * @param string $method Method or function name
1928 * @param string $message Error message
1929 * @throws MWException
1931 protected static function dieDebug( $method, $message ) {
1932 throw new MWException( "Internal error in $method: $message" );
1937 /************************************************************************//**
1938 * @name Help message generation
1943 * Return the description message.
1945 * @return string|array|Message
1947 protected function getDescriptionMessage() {
1948 return "apihelp-{$this->getModulePath()}-description";
1952 * Get final module description, after hooks have had a chance to tweak it as
1955 * @since 1.25, returns Message[] rather than string[]
1958 public function getFinalDescription() {
1959 $desc = $this->getDescription();
1960 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
1961 $desc = self
::escapeWikiText( $desc );
1962 if ( is_array( $desc ) ) {
1963 $desc = join( "\n", $desc );
1965 $desc = (string)$desc;
1968 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1969 $this->getModulePrefix(),
1970 $this->getModuleName(),
1971 $this->getModulePath(),
1973 if ( !$msg->exists() ) {
1974 $msg = $this->msg( 'api-help-fallback-description', $desc );
1976 $msgs = array( $msg );
1978 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1984 * Get final list of parameters, after hooks have had a chance to
1985 * tweak it as needed.
1987 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1988 * @return array|bool False on no parameters
1989 * @since 1.21 $flags param added
1991 public function getFinalParams( $flags = 0 ) {
1992 $params = $this->getAllowedParams( $flags );
1997 if ( $this->needsToken() ) {
1998 $params['token'] = array(
1999 ApiBase
::PARAM_TYPE
=> 'string',
2000 ApiBase
::PARAM_REQUIRED
=> true,
2001 ApiBase
::PARAM_HELP_MSG
=> array(
2002 'api-help-param-token',
2003 $this->needsToken(),
2005 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2008 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2014 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2017 * @since 1.25, returns array of Message[] rather than array of string[]
2018 * @return array Keys are parameter names, values are arrays of Message objects
2020 public function getFinalParamDescription() {
2021 $desc = $this->getParamDescription();
2022 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2027 $desc = self
::escapeWikiText( $desc );
2029 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2031 foreach ( $params as $param => $settings ) {
2032 if ( !is_array( $settings ) ) {
2033 $settings = array();
2036 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2037 if ( is_array( $d ) ) {
2038 // Special handling for prop parameters
2039 $d = array_map( function ( $line ) {
2040 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2041 $line = "\n;{$m[1]}:{$m[2]}";
2045 $d = join( ' ', $d );
2048 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2049 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2051 $msg = $this->msg( "apihelp-{$this->getModulePath()}-param-{$param}" );
2052 if ( !$msg->exists() ) {
2053 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2056 $msg = ApiBase
::makeMessage( $msg, $this->getContext(), array(
2057 $this->getModulePrefix(),
2059 $this->getModuleName(),
2060 $this->getModulePath(),
2063 $this->dieDebug( __METHOD__
,
2064 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2066 $msgs[$param] = array( $msg );
2068 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2069 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2070 $this->dieDebug( __METHOD__
,
2071 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2073 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2074 $m = ApiBase
::makeMessage( $m, $this->getContext(), array(
2075 $this->getModulePrefix(),
2077 $this->getModuleName(),
2078 $this->getModulePath(),
2081 $msgs[$param][] = $m;
2083 $this->dieDebug( __METHOD__
,
2084 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2090 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2096 * Generates the list of flags for the help screen and for action=paraminfo
2098 * Corresponding messages: api-help-flag-deprecated,
2099 * api-help-flag-internal, api-help-flag-readrights,
2100 * api-help-flag-writerights, api-help-flag-mustbeposted
2104 protected function getHelpFlags() {
2107 if ( $this->isDeprecated() ) {
2108 $flags[] = 'deprecated';
2110 if ( $this->isInternal() ) {
2111 $flags[] = 'internal';
2113 if ( $this->isReadMode() ) {
2114 $flags[] = 'readrights';
2116 if ( $this->isWriteMode() ) {
2117 $flags[] = 'writerights';
2119 if ( $this->mustBePosted() ) {
2120 $flags[] = 'mustbeposted';
2127 * Called from ApiHelp before the pieces are joined together and returned.
2129 * This exists mainly for ApiMain to add the Permissions and Credits
2130 * sections. Other modules probably don't need it.
2132 * @param string[] &$help Array of help data
2133 * @param array $options Options passed to ApiHelp::getHelp
2135 public function modifyHelp( array &$help, array $options ) {
2140 /************************************************************************//**
2146 * Profiling: total module execution time
2148 private $mTimeIn = 0, $mModuleTime = 0;
2151 * Get the name of the module as shown in the profiler log
2153 * @param DatabaseBase|bool $db
2157 public function getModuleProfileName( $db = false ) {
2159 return 'API:' . $this->mModuleName
. '-DB';
2162 return 'API:' . $this->mModuleName
;
2166 * Start module profiling
2168 public function profileIn() {
2169 if ( $this->mTimeIn
!== 0 ) {
2170 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2172 $this->mTimeIn
= microtime( true );
2173 wfProfileIn( $this->getModuleProfileName() );
2177 * End module profiling
2179 public function profileOut() {
2180 if ( $this->mTimeIn
=== 0 ) {
2181 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2183 if ( $this->mDBTimeIn
!== 0 ) {
2186 'Must be called after database profiling is done with profileDBOut()'
2190 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2192 wfProfileOut( $this->getModuleProfileName() );
2196 * When modules crash, sometimes it is needed to do a profileOut() regardless
2197 * of the profiling state the module was in. This method does such cleanup.
2199 public function safeProfileOut() {
2200 if ( $this->mTimeIn
!== 0 ) {
2201 if ( $this->mDBTimeIn
!== 0 ) {
2202 $this->profileDBOut();
2204 $this->profileOut();
2209 * Total time the module was executed
2212 public function getProfileTime() {
2213 if ( $this->mTimeIn
!== 0 ) {
2214 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2217 return $this->mModuleTime
;
2221 * Profiling: database execution time
2223 private $mDBTimeIn = 0, $mDBTime = 0;
2226 * Start module profiling
2228 public function profileDBIn() {
2229 if ( $this->mTimeIn
=== 0 ) {
2232 'Must be called while profiling the entire module with profileIn()'
2235 if ( $this->mDBTimeIn
!== 0 ) {
2236 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2238 $this->mDBTimeIn
= microtime( true );
2239 wfProfileIn( $this->getModuleProfileName( true ) );
2243 * End database profiling
2245 public function profileDBOut() {
2246 if ( $this->mTimeIn
=== 0 ) {
2247 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2248 'the entire module with profileIn()' );
2250 if ( $this->mDBTimeIn
=== 0 ) {
2251 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2254 $time = microtime( true ) - $this->mDBTimeIn
;
2255 $this->mDBTimeIn
= 0;
2257 $this->mDBTime +
= $time;
2258 $this->getMain()->mDBTime +
= $time;
2259 wfProfileOut( $this->getModuleProfileName( true ) );
2263 * Total time the module used the database
2266 public function getProfileDBTime() {
2267 if ( $this->mDBTimeIn
!== 0 ) {
2268 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2271 return $this->mDBTime
;
2275 * Write logging information for API features to a debug log, for usage
2277 * @param string $feature Feature being used.
2279 protected function logFeatureUsage( $feature ) {
2280 $request = $this->getRequest();
2281 $s = '"' . addslashes( $feature ) . '"' .
2282 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2283 ' "' . $request->getIP() . '"' .
2284 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2285 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2286 wfDebugLog( 'api-feature-usage', $s, 'private' );
2291 /************************************************************************//**
2296 /// @deprecated since 1.24
2297 const PROP_ROOT
= 'ROOT';
2298 /// @deprecated since 1.24
2299 const PROP_LIST
= 'LIST';
2300 /// @deprecated since 1.24
2301 const PROP_TYPE
= 0;
2302 /// @deprecated since 1.24
2303 const PROP_NULLABLE
= 1;
2306 * Formerly returned a string that identifies the version of the extending
2307 * class. Typically included the class name, the svn revision, timestamp,
2308 * and last author. Usually done with SVN's Id keyword
2310 * @deprecated since 1.21, version string is no longer supported
2313 public function getVersion() {
2314 wfDeprecated( __METHOD__
, '1.21' );
2319 * Formerly used to fetch a list of possible properites in the result,
2320 * somehow organized with respect to the prop parameter that causes them to
2321 * be returned. The specific semantics of the return value was never
2322 * specified. Since this was never possible to be accurately updated, it
2325 * @deprecated since 1.24
2326 * @return array|bool
2328 protected function getResultProperties() {
2329 wfDeprecated( __METHOD__
, '1.24' );
2334 * @see self::getResultProperties()
2335 * @deprecated since 1.24
2336 * @return array|bool
2338 public function getFinalResultProperties() {
2339 wfDeprecated( __METHOD__
, '1.24' );
2344 * @see self::getResultProperties()
2345 * @deprecated since 1.24
2347 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2348 wfDeprecated( __METHOD__
, '1.24' );
2352 * @see self::getPossibleErrors()
2353 * @deprecated since 1.24
2356 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2357 wfDeprecated( __METHOD__
, '1.24' );
2362 * @see self::getPossibleErrors()
2363 * @deprecated since 1.24
2366 public function getRequireMaxOneParameterErrorMessages( $params ) {
2367 wfDeprecated( __METHOD__
, '1.24' );
2372 * @see self::getPossibleErrors()
2373 * @deprecated since 1.24
2376 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2377 wfDeprecated( __METHOD__
, '1.24' );
2382 * @see self::getPossibleErrors()
2383 * @deprecated since 1.24
2386 public function getTitleOrPageIdErrorMessage() {
2387 wfDeprecated( __METHOD__
, '1.24' );
2392 * This formerly attempted to return a list of all possible errors returned
2393 * by the module. However, this was impossible to maintain in many cases
2394 * since errors could come from other areas of MediaWiki and in some cases
2395 * from arbitrary extension hooks. Since a partial list claiming to be
2396 * comprehensive is unlikely to be useful, it was removed.
2398 * @deprecated since 1.24
2401 public function getPossibleErrors() {
2402 wfDeprecated( __METHOD__
, '1.24' );
2407 * @see self::getPossibleErrors()
2408 * @deprecated since 1.24
2411 public function getFinalPossibleErrors() {
2412 wfDeprecated( __METHOD__
, '1.24' );
2417 * @see self::getPossibleErrors()
2418 * @deprecated since 1.24
2421 public function parseErrors( $errors ) {
2422 wfDeprecated( __METHOD__
, '1.24' );
2427 * Returns the description string for this module
2429 * Ignored if an i18n message exists for
2430 * "apihelp-{$this->getModulePathString()}-description".
2432 * @deprecated since 1.25
2433 * @return Message|string|array
2435 protected function getDescription() {
2440 * Returns an array of parameter descriptions.
2442 * For each parameter, ignored if an i18n message exists for the parameter.
2443 * By default that message is
2444 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2445 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2446 * self::getFinalParams().
2448 * @deprecated since 1.25
2449 * @return array|bool False on no parameter descriptions
2451 protected function getParamDescription() {
2456 * Returns usage examples for this module.
2458 * Return value as an array is either:
2459 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2461 * - sequential numeric keys with even-numbered keys being display-text
2462 * and odd-numbered keys being partial urls
2463 * - partial URLs as keys with display-text (string or array-to-be-joined)
2465 * Return value as a string is the same as an array with a numeric key and
2466 * that value, and boolean false means "no examples".
2468 * @deprecated since 1.25, use getExamplesMessages() instead
2469 * @return bool|string|array
2471 protected function getExamples() {
2476 * Generates help message for this module, or false if there is no description
2477 * @deprecated since 1.25
2478 * @return string|bool
2480 public function makeHelpMsg() {
2481 wfDeprecated( __METHOD__
, '1.25' );
2482 static $lnPrfx = "\n ";
2484 $msg = $this->getFinalDescription();
2486 if ( $msg !== false ) {
2488 if ( !is_array( $msg ) ) {
2493 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2495 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2497 if ( $this->isReadMode() ) {
2498 $msg .= "\nThis module requires read rights";
2500 if ( $this->isWriteMode() ) {
2501 $msg .= "\nThis module requires write rights";
2503 if ( $this->mustBePosted() ) {
2504 $msg .= "\nThis module only accepts POST requests";
2506 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2507 $this->mustBePosted()
2513 $paramsMsg = $this->makeHelpMsgParameters();
2514 if ( $paramsMsg !== false ) {
2515 $msg .= "Parameters:\n$paramsMsg";
2518 $examples = $this->getExamples();
2520 if ( !is_array( $examples ) ) {
2525 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2526 foreach ( $examples as $k => $v ) {
2527 if ( is_numeric( $k ) ) {
2530 if ( is_array( $v ) ) {
2531 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2533 $msgExample = " $v";
2536 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2546 * @deprecated since 1.25
2547 * @param string $item
2550 private function indentExampleText( $item ) {
2555 * @deprecated since 1.25
2556 * @param string $prefix Text to split output items
2557 * @param string $title What is being output
2558 * @param string|array $input
2561 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2562 wfDeprecated( __METHOD__
, '1.25' );
2563 if ( $input === false ) {
2566 if ( !is_array( $input ) ) {
2567 $input = array( $input );
2570 if ( count( $input ) > 0 ) {
2572 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2576 $msg .= implode( $prefix, $input ) . "\n";
2585 * Generates the parameter descriptions for this module, to be displayed in the
2587 * @deprecated since 1.25
2588 * @return string|bool
2590 public function makeHelpMsgParameters() {
2591 wfDeprecated( __METHOD__
, '1.25' );
2592 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2595 $paramsDescription = $this->getFinalParamDescription();
2597 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2598 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2599 foreach ( $params as $paramName => $paramSettings ) {
2600 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2601 if ( is_array( $desc ) ) {
2602 $desc = implode( $paramPrefix, $desc );
2606 if ( !is_array( $paramSettings ) ) {
2607 $paramSettings = array(
2608 self
::PARAM_DFLT
=> $paramSettings,
2612 //handle missing type
2613 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2614 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2615 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2617 if ( is_bool( $dflt ) ) {
2618 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2619 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2620 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2621 } elseif ( is_int( $dflt ) ) {
2622 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2626 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2627 && $paramSettings[self
::PARAM_DEPRECATED
]
2629 $desc = "DEPRECATED! $desc";
2632 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2633 && $paramSettings[self
::PARAM_REQUIRED
]
2635 $desc .= $paramPrefix . "This parameter is required";
2638 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2639 ?
$paramSettings[self
::PARAM_TYPE
]
2641 if ( isset( $type ) ) {
2642 $hintPipeSeparated = true;
2643 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2644 ?
$paramSettings[self
::PARAM_ISMULTI
]
2647 $prompt = 'Values (separate with \'|\'): ';
2649 $prompt = 'One value: ';
2652 if ( $type === 'submodule' ) {
2653 $type = $this->getModuleManager()->getNames( $paramName );
2656 if ( is_array( $type ) ) {
2658 $nothingPrompt = '';
2659 foreach ( $type as $t ) {
2661 $nothingPrompt = 'Can be empty, or ';
2666 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2667 $choicesstring = implode( ', ', $choices );
2668 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2669 $hintPipeSeparated = false;
2673 // Special handling because namespaces are
2674 // type-limited, yet they are not given
2675 $desc .= $paramPrefix . $prompt;
2676 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2677 100, $descWordwrap );
2678 $hintPipeSeparated = false;
2681 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2682 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2683 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2685 $desc .= ' allowed';
2688 $s = $multi ?
's' : '';
2689 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2690 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2691 if ( $hasMin ||
$hasMax ) {
2693 $intRangeStr = "The value$s must be no less than " .
2694 "{$paramSettings[self::PARAM_MIN]}";
2695 } elseif ( !$hasMin ) {
2696 $intRangeStr = "The value$s must be no more than " .
2697 "{$paramSettings[self::PARAM_MAX]}";
2699 $intRangeStr = "The value$s must be between " .
2700 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2703 $desc .= $paramPrefix . $intRangeStr;
2707 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2713 if ( $hintPipeSeparated ) {
2714 $desc .= $paramPrefix . "Separate values with '|'";
2717 $isArray = is_array( $type );
2719 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2721 $desc .= $paramPrefix . "Maximum number of values " .
2722 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2727 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2728 if ( !is_null( $default ) && $default !== false ) {
2729 $desc .= $paramPrefix . "Default: $default";
2732 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2745 * For really cool vim folding this needs to be at the end:
2746 * vim: foldmarker=@{,@} foldmethod=marker