5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Self-documentation: code to allow the API to document its own state
39 abstract class ApiBase
extends ContextSource
{
40 // These constants allow modules to specify exactly how to treat incoming parameters.
42 // Default value of the parameter
44 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
45 const PARAM_ISMULTI
= 1;
46 // Can be either a string type (e.g.: 'integer') or an array of allowed values
48 // Max value allowed for a parameter. Only applies if TYPE='integer'
50 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
52 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
54 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
55 const PARAM_ALLOW_DUPLICATES
= 6;
56 // Boolean, is the parameter deprecated (will show a warning)
57 const PARAM_DEPRECATED
= 7;
59 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
61 // Boolean, if MIN/MAX are set, enforce (die) these?
62 // Only applies if TYPE='integer' Use with extreme caution
63 const PARAM_RANGE_ENFORCE
= 9;
65 // Specify an alternative i18n message for this help parameter.
66 // Value is $msg for ApiBase::makeMessage()
67 const PARAM_HELP_MSG
= 10;
69 // Specify additional i18n messages to append to the normal message. Value
70 // is an array of $msg for ApiBase::makeMessage()
71 const PARAM_HELP_MSG_APPEND
= 11;
73 // Specify additional information tags for the parameter. Value is an array
74 // of arrays, with the first member being the 'tag' for the info and the
75 // remaining members being the values. In the help, this is formatted using
76 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
77 // comma-joined list of values, $3 = module prefix.
78 const PARAM_HELP_MSG_INFO
= 12;
80 // When PARAM_TYPE is an array, this may be an array mapping those values
81 // to page titles which will be linked in the help.
82 const PARAM_VALUE_LINKS
= 13;
84 // When PARAM_TYPE is an array, this is an array mapping those values to
85 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
86 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
87 const PARAM_HELP_MSG_PER_VALUE
= 14;
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 * @note Do not use this just because you don't want to support non-json
161 * formats. This should be used only when there is a fundamental
162 * requirement for a specific format.
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 error formatter
471 * @return ApiErrorFormatter
473 public function getErrorFormatter() {
474 // Main module has getErrorFormatter() method overridden
475 // Safety - avoid infinite loop:
476 if ( $this->isMain() ) {
477 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
480 return $this->getMain()->getErrorFormatter();
484 * Gets a default slave database connection object
485 * @return DatabaseBase
487 protected function getDB() {
488 if ( !isset( $this->mSlaveDB
) ) {
489 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
492 return $this->mSlaveDB
;
496 * Get the continuation manager
497 * @return ApiContinuationManager|null
499 public function getContinuationManager() {
500 // Main module has getContinuationManager() method overridden
501 // Safety - avoid infinite loop:
502 if ( $this->isMain() ) {
503 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
506 return $this->getMain()->getContinuationManager();
510 * Set the continuation manager
511 * @param ApiContinuationManager|null
513 public function setContinuationManager( $manager ) {
514 // Main module has setContinuationManager() method overridden
515 // Safety - avoid infinite loop:
516 if ( $this->isMain() ) {
517 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
520 $this->getMain()->setContinuationManager( $manager );
525 /************************************************************************//**
526 * @name Parameter handling
531 * This method mangles parameter name based on the prefix supplied to the constructor.
532 * Override this method to change parameter name during runtime
533 * @param string $paramName Parameter name
534 * @return string Prefixed parameter name
536 public function encodeParamName( $paramName ) {
537 return $this->mModulePrefix
. $paramName;
541 * Using getAllowedParams(), this function makes an array of the values
542 * provided by the user, with key being the name of the variable, and
543 * value - validated value from user or default. limits will not be
544 * parsed if $parseLimit is set to false; use this when the max
545 * limit is not definitive yet, e.g. when getting revisions.
546 * @param bool $parseLimit True by default
549 public function extractRequestParams( $parseLimit = true ) {
550 // Cache parameters, for performance and to avoid bug 24564.
551 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
552 $params = $this->getFinalParams();
555 if ( $params ) { // getFinalParams() can return false
556 foreach ( $params as $paramName => $paramSettings ) {
557 $results[$paramName] = $this->getParameterFromSettings(
558 $paramName, $paramSettings, $parseLimit );
561 $this->mParamCache
[$parseLimit] = $results;
564 return $this->mParamCache
[$parseLimit];
568 * Get a value for the given parameter
569 * @param string $paramName Parameter name
570 * @param bool $parseLimit See extractRequestParams()
571 * @return mixed Parameter value
573 protected function getParameter( $paramName, $parseLimit = true ) {
574 $params = $this->getFinalParams();
575 $paramSettings = $params[$paramName];
577 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
581 * Die if none or more than one 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 exactly one must be set
586 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
587 $required = func_get_args();
588 array_shift( $required );
589 $p = $this->getModulePrefix();
591 $intersection = array_intersect( array_keys( array_filter( $params,
592 array( $this, "parameterNotEmpty" ) ) ), $required );
594 if ( count( $intersection ) > 1 ) {
596 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
598 } elseif ( count( $intersection ) == 0 ) {
600 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
607 * Die if more than one of a certain set of parameters is set and not false.
609 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
610 * @param string $required,... Names of parameters of which at most one must be set
612 public function requireMaxOneParameter( $params, $required /*...*/ ) {
613 $required = func_get_args();
614 array_shift( $required );
615 $p = $this->getModulePrefix();
617 $intersection = array_intersect( array_keys( array_filter( $params,
618 array( $this, "parameterNotEmpty" ) ) ), $required );
620 if ( count( $intersection ) > 1 ) {
622 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
629 * Die if none of a certain set of parameters is set and not false.
632 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
633 * @param string $required,... Names of parameters of which at least one must be set
635 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
636 $required = func_get_args();
637 array_shift( $required );
638 $p = $this->getModulePrefix();
640 $intersection = array_intersect(
641 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
645 if ( count( $intersection ) == 0 ) {
646 $this->dieUsage( "At least one of the parameters {$p}" .
647 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
652 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
654 * @param object $x Parameter to check is not null/false
657 private function parameterNotEmpty( $x ) {
658 return !is_null( $x ) && $x !== false;
662 * Get a WikiPage object from a title or pageid param, if possible.
663 * Can die, if no param is set or if the title or page id is not valid.
665 * @param array $params
666 * @param bool|string $load Whether load the object's state from the database:
667 * - false: don't load (if the pageid is given, it will still be loaded)
668 * - 'fromdb': load from a slave database
669 * - 'fromdbmaster': load from the master database
672 public function getTitleOrPageId( $params, $load = false ) {
673 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
676 if ( isset( $params['title'] ) ) {
677 $titleObj = Title
::newFromText( $params['title'] );
678 if ( !$titleObj ||
$titleObj->isExternal() ) {
679 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
681 if ( !$titleObj->canExist() ) {
682 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
684 $pageObj = WikiPage
::factory( $titleObj );
685 if ( $load !== false ) {
686 $pageObj->loadPageData( $load );
688 } elseif ( isset( $params['pageid'] ) ) {
689 if ( $load === false ) {
692 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
694 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
702 * Return true if we're to watch the page, false if not, null if no change.
703 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
704 * @param Title $titleObj The page under consideration
705 * @param string $userOption The user option to consider when $watchlist=preferences.
706 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
709 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
711 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
713 switch ( $watchlist ) {
721 # If the user is already watching, don't bother checking
722 if ( $userWatching ) {
725 # If no user option was passed, use watchdefault and watchcreations
726 if ( is_null( $userOption ) ) {
727 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
728 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
731 # Watch the article based on the user preference
732 return $this->getUser()->getBoolOption( $userOption );
735 return $userWatching;
738 return $userWatching;
743 * Using the settings determine the value for the given parameter
745 * @param string $paramName Parameter name
746 * @param array|mixed $paramSettings Default value or an array of settings
747 * using PARAM_* constants.
748 * @param bool $parseLimit Parse limit?
749 * @return mixed Parameter value
751 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
752 // Some classes may decide to change parameter names
753 $encParamName = $this->encodeParamName( $paramName );
755 if ( !is_array( $paramSettings ) ) {
756 $default = $paramSettings;
758 $type = gettype( $paramSettings );
763 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
764 ?
$paramSettings[self
::PARAM_DFLT
]
766 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
767 ?
$paramSettings[self
::PARAM_ISMULTI
]
769 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
770 ?
$paramSettings[self
::PARAM_TYPE
]
772 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
773 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
775 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
776 ?
$paramSettings[self
::PARAM_DEPRECATED
]
778 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
779 ?
$paramSettings[self
::PARAM_REQUIRED
]
782 // When type is not given, and no choices, the type is the same as $default
783 if ( !isset( $type ) ) {
784 if ( isset( $default ) ) {
785 $type = gettype( $default );
787 $type = 'NULL'; // allow everything
792 if ( $type == 'boolean' ) {
793 if ( isset( $default ) && $default !== false ) {
794 // Having a default value of anything other than 'false' is not allowed
797 "Boolean param $encParamName's default is set to '$default'. " .
798 "Boolean parameters must default to false."
802 $value = $this->getMain()->getCheck( $encParamName );
803 } elseif ( $type == 'upload' ) {
804 if ( isset( $default ) ) {
805 // Having a default value is not allowed
808 "File upload param $encParamName's default is set to " .
809 "'$default'. File upload parameters may not have a default." );
812 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
814 $value = $this->getMain()->getUpload( $encParamName );
815 if ( !$value->exists() ) {
816 // This will get the value without trying to normalize it
817 // (because trying to normalize a large binary file
818 // accidentally uploaded as a field fails spectacularly)
819 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
820 if ( $value !== null ) {
822 "File upload param $encParamName is not a file upload; " .
823 "be sure to use multipart/form-data for your POST and include " .
824 "a filename in the Content-Disposition header.",
825 "badupload_{$encParamName}"
830 $value = $this->getMain()->getVal( $encParamName, $default );
832 if ( isset( $value ) && $type == 'namespace' ) {
833 $type = MWNamespace
::getValidNamespaces();
835 if ( isset( $value ) && $type == 'submodule' ) {
836 $type = $this->getModuleManager()->getNames( $paramName );
840 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
841 $value = $this->parseMultiValue(
845 is_array( $type ) ?
$type : null
849 // More validation only when choices were not given
850 // choices were validated in parseMultiValue()
851 if ( isset( $value ) ) {
852 if ( !is_array( $type ) ) {
854 case 'NULL': // nothing to do
857 if ( $required && $value === '' ) {
858 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
861 case 'integer': // Force everything using intval() and optionally validate limits
862 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
863 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
864 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
865 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
867 if ( is_array( $value ) ) {
868 $value = array_map( 'intval', $value );
869 if ( !is_null( $min ) ||
!is_null( $max ) ) {
870 foreach ( $value as &$v ) {
871 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
875 $value = intval( $value );
876 if ( !is_null( $min ) ||
!is_null( $max ) ) {
877 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
882 if ( !$parseLimit ) {
883 // Don't do any validation whatsoever
886 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
887 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
891 "MAX1 or MAX2 are not defined for the limit $encParamName"
895 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
897 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
898 if ( $value == 'max' ) {
899 $value = $this->getMain()->canApiHighLimits()
900 ?
$paramSettings[self
::PARAM_MAX2
]
901 : $paramSettings[self
::PARAM_MAX
];
902 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
904 $value = intval( $value );
905 $this->validateLimit(
909 $paramSettings[self
::PARAM_MAX
],
910 $paramSettings[self
::PARAM_MAX2
]
916 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
920 if ( is_array( $value ) ) {
921 foreach ( $value as $key => $val ) {
922 $value[$key] = $this->validateTimestamp( $val, $encParamName );
925 $value = $this->validateTimestamp( $value, $encParamName );
929 if ( is_array( $value ) ) {
930 foreach ( $value as $key => $val ) {
931 $value[$key] = $this->validateUser( $val, $encParamName );
934 $value = $this->validateUser( $value, $encParamName );
937 case 'upload': // nothing to do
940 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
944 // Throw out duplicates if requested
945 if ( !$dupes && is_array( $value ) ) {
946 $value = array_unique( $value );
949 // Set a warning if a deprecated parameter has been passed
950 if ( $deprecated && $value !== false ) {
951 $this->setWarning( "The $encParamName parameter has been deprecated." );
953 } elseif ( $required ) {
954 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
961 * Return an array of values that were given in a 'a|b|c' notation,
962 * after it optionally validates them against the list allowed values.
964 * @param string $valueName The name of the parameter (for error
966 * @param mixed $value The value being parsed
967 * @param bool $allowMultiple Can $value contain more than one value
969 * @param string[]|null $allowedValues An array of values to check against. If
970 * null, all values are accepted.
971 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
973 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
974 if ( trim( $value ) === '' && $allowMultiple ) {
978 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
979 // because it unstubs $wgUser
980 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
981 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
985 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
986 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
987 "the limit is $sizeLimit" );
990 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
991 // Bug 33482 - Allow entries with | in them for non-multiple values
992 if ( in_array( $value, $allowedValues, true ) ) {
996 $possibleValues = is_array( $allowedValues )
997 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1000 "Only one $possibleValues is allowed for parameter '$valueName'",
1001 "multival_$valueName"
1005 if ( is_array( $allowedValues ) ) {
1006 // Check for unknown values
1007 $unknown = array_diff( $valuesList, $allowedValues );
1008 if ( count( $unknown ) ) {
1009 if ( $allowMultiple ) {
1010 $s = count( $unknown ) > 1 ?
's' : '';
1011 $vals = implode( ", ", $unknown );
1012 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1015 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1016 "unknown_$valueName"
1020 // Now throw them out
1021 $valuesList = array_intersect( $valuesList, $allowedValues );
1024 return $allowMultiple ?
$valuesList : $valuesList[0];
1028 * Validate the value against the minimum and user/bot maximum limits.
1029 * Prints usage info on failure.
1030 * @param string $paramName Parameter name
1031 * @param int $value Parameter value
1032 * @param int|null $min Minimum value
1033 * @param int|null $max Maximum value for users
1034 * @param int $botMax Maximum value for sysops/bots
1035 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1037 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1038 if ( !is_null( $min ) && $value < $min ) {
1040 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1041 $this->warnOrDie( $msg, $enforceLimits );
1045 // Minimum is always validated, whereas maximum is checked only if not
1046 // running in internal call mode
1047 if ( $this->getMain()->isInternalMode() ) {
1051 // Optimization: do not check user's bot status unless really needed -- skips db query
1052 // assumes $botMax >= $max
1053 if ( !is_null( $max ) && $value > $max ) {
1054 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1055 if ( $value > $botMax ) {
1056 $msg = $this->encodeParamName( $paramName ) .
1057 " may not be over $botMax (set to $value) for bots or sysops";
1058 $this->warnOrDie( $msg, $enforceLimits );
1062 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1063 $this->warnOrDie( $msg, $enforceLimits );
1070 * Validate and normalize of parameters of type 'timestamp'
1071 * @param string $value Parameter value
1072 * @param string $encParamName Parameter name
1073 * @return string Validated and normalized parameter
1075 protected function validateTimestamp( $value, $encParamName ) {
1076 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1077 if ( $unixTimestamp === false ) {
1079 "Invalid value '$value' for timestamp parameter $encParamName",
1080 "badtimestamp_{$encParamName}"
1084 return wfTimestamp( TS_MW
, $unixTimestamp );
1088 * Validate the supplied token.
1091 * @param string $token Supplied token
1092 * @param array $params All supplied parameters for the module
1094 * @throws MWException
1096 final public function validateToken( $token, array $params ) {
1097 $tokenType = $this->needsToken();
1098 $salts = ApiQueryTokens
::getTokenTypeSalts();
1099 if ( !isset( $salts[$tokenType] ) ) {
1100 throw new MWException(
1101 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1102 'without registering it'
1106 if ( $this->getUser()->matchEditToken(
1114 $webUiSalt = $this->getWebUITokenSalt( $params );
1115 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1127 * Validate and normalize of parameters of type 'user'
1128 * @param string $value Parameter value
1129 * @param string $encParamName Parameter name
1130 * @return string Validated and normalized parameter
1132 private function validateUser( $value, $encParamName ) {
1133 $title = Title
::makeTitleSafe( NS_USER
, $value );
1134 if ( $title === null ) {
1136 "Invalid value '$value' for user parameter $encParamName",
1137 "baduser_{$encParamName}"
1141 return $title->getText();
1146 /************************************************************************//**
1147 * @name Utility methods
1152 * Set a watch (or unwatch) based the based on a watchlist parameter.
1153 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1154 * @param Title $titleObj The article's title to change
1155 * @param string $userOption The user option to consider when $watch=preferences
1157 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1158 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1159 if ( $value === null ) {
1163 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1167 * Truncate an array to a certain length.
1168 * @param array $arr Array to truncate
1169 * @param int $limit Maximum length
1170 * @return bool True if the array was truncated, false otherwise
1172 public static function truncateArray( &$arr, $limit ) {
1174 while ( count( $arr ) > $limit ) {
1183 * Gets the user for whom to get the watchlist
1185 * @param array $params
1188 public function getWatchlistUser( $params ) {
1189 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1190 $user = User
::newFromName( $params['owner'], false );
1191 if ( !( $user && $user->getId() ) ) {
1192 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1194 $token = $user->getOption( 'watchlisttoken' );
1195 if ( $token == '' ||
$token != $params['token'] ) {
1197 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1202 if ( !$this->getUser()->isLoggedIn() ) {
1203 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1205 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1206 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1208 $user = $this->getUser();
1215 * A subset of wfEscapeWikiText for BC texts
1218 * @param string|array $v
1219 * @return string|array
1221 private static function escapeWikiText( $v ) {
1222 if ( is_array( $v ) ) {
1223 return array_map( 'self::escapeWikiText', $v );
1225 return strtr( $v, array(
1226 '__' => '__', '{' => '{', '}' => '}',
1227 '[[Category:' => '[[:Category:',
1228 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1234 * Create a Message from a string or array
1236 * A string is used as a message key. An array has the message key as the
1237 * first value and message parameters as subsequent values.
1240 * @param string|array|Message $msg
1241 * @param IContextSource $context
1242 * @param array $params
1243 * @return Message|null
1245 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1246 if ( is_string( $msg ) ) {
1247 $msg = wfMessage( $msg );
1248 } elseif ( is_array( $msg ) ) {
1249 $msg = call_user_func_array( 'wfMessage', $msg );
1251 if ( !$msg instanceof Message
) {
1255 $msg->setContext( $context );
1257 $msg->params( $params );
1265 /************************************************************************//**
1266 * @name Warning and error reporting
1271 * Set warning section for this module. Users should monitor this
1272 * section to notice any changes in API. Multiple calls to this
1273 * function will result in the warning messages being separated by
1275 * @param string $warning Warning message
1277 public function setWarning( $warning ) {
1278 $msg = new ApiRawMessage( $warning, 'warning' );
1279 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1283 * Adds a warning to the output, else dies
1285 * @param string $msg Message to show as a warning, or error message if dying
1286 * @param bool $enforceLimits Whether this is an enforce (die)
1288 private function warnOrDie( $msg, $enforceLimits = false ) {
1289 if ( $enforceLimits ) {
1290 $this->dieUsage( $msg, 'integeroutofrange' );
1293 $this->setWarning( $msg );
1297 * Throw a UsageException, which will (if uncaught) call the main module's
1298 * error handler and die with an error message.
1300 * @param string $description One-line human-readable description of the
1301 * error condition, e.g., "The API requires a valid action parameter"
1302 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1303 * automated identification of the error, e.g., 'unknown_action'
1304 * @param int $httpRespCode HTTP response code
1305 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1306 * @throws UsageException
1308 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1309 throw new UsageException(
1311 $this->encodeParamName( $errorCode ),
1318 * Get error (as code, string) from a Status object.
1321 * @param Status $status
1322 * @return array Array of code and error string
1323 * @throws MWException
1325 public function getErrorFromStatus( $status ) {
1326 if ( $status->isGood() ) {
1327 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1330 $errors = $status->getErrorsArray();
1332 // No errors? Assume the warnings should be treated as errors
1333 $errors = $status->getWarningsArray();
1336 // Still no errors? Punt
1337 $errors = array( array( 'unknownerror-nocode' ) );
1340 // Cannot use dieUsageMsg() because extensions might return custom
1342 if ( $errors[0] instanceof Message
) {
1344 $code = $msg->getKey();
1346 $code = array_shift( $errors[0] );
1347 $msg = wfMessage( $code, $errors[0] );
1349 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1350 // Translate message to code, for backwards compatibility
1351 $code = ApiBase
::$messageMap[$code]['code'];
1354 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1358 * Throw a UsageException based on the errors in the Status object.
1361 * @param Status $status
1362 * @throws MWException
1364 public function dieStatus( $status ) {
1366 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1367 $this->dieUsage( $msg, $code );
1370 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1372 * Array that maps message keys to error messages. $1 and friends are replaced.
1374 public static $messageMap = array(
1375 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1376 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1377 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1379 // Messages from Title::getUserPermissionsErrors()
1380 'ns-specialprotected' => array(
1381 'code' => 'unsupportednamespace',
1382 'info' => "Pages in the Special namespace can't be edited"
1384 'protectedinterface' => array(
1385 'code' => 'protectednamespace-interface',
1386 'info' => "You're not allowed to edit interface messages"
1388 'namespaceprotected' => array(
1389 'code' => 'protectednamespace',
1390 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1392 'customcssprotected' => array(
1393 'code' => 'customcssprotected',
1394 'info' => "You're not allowed to edit custom CSS pages"
1396 'customjsprotected' => array(
1397 'code' => 'customjsprotected',
1398 'info' => "You're not allowed to edit custom JavaScript pages"
1400 'cascadeprotected' => array(
1401 'code' => 'cascadeprotected',
1402 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1404 'protectedpagetext' => array(
1405 'code' => 'protectedpage',
1406 'info' => "The \"\$1\" right is required to edit this page"
1408 'protect-cantedit' => array(
1409 'code' => 'cantedit',
1410 'info' => "You can't protect this page because you can't edit it"
1412 'deleteprotected' => array(
1413 'code' => 'cantedit',
1414 'info' => "You can't delete this page because it has been protected"
1416 'badaccess-group0' => array(
1417 'code' => 'permissiondenied',
1418 'info' => "Permission denied"
1419 ), // Generic permission denied message
1420 'badaccess-groups' => array(
1421 'code' => 'permissiondenied',
1422 'info' => "Permission denied"
1424 'titleprotected' => array(
1425 'code' => 'protectedtitle',
1426 'info' => "This title has been protected from creation"
1428 'nocreate-loggedin' => array(
1429 'code' => 'cantcreate',
1430 'info' => "You don't have permission to create new pages"
1432 'nocreatetext' => array(
1433 'code' => 'cantcreate-anon',
1434 'info' => "Anonymous users can't create new pages"
1436 'movenologintext' => array(
1437 'code' => 'cantmove-anon',
1438 'info' => "Anonymous users can't move pages"
1440 'movenotallowed' => array(
1441 'code' => 'cantmove',
1442 'info' => "You don't have permission to move pages"
1444 'confirmedittext' => array(
1445 'code' => 'confirmemail',
1446 'info' => "You must confirm your email address before you can edit"
1448 'blockedtext' => array(
1449 'code' => 'blocked',
1450 'info' => "You have been blocked from editing"
1452 'autoblockedtext' => array(
1453 'code' => 'autoblocked',
1454 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1457 // Miscellaneous interface messages
1458 'actionthrottledtext' => array(
1459 'code' => 'ratelimited',
1460 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1462 'alreadyrolled' => array(
1463 'code' => 'alreadyrolled',
1464 'info' => "The page you tried to rollback was already rolled back"
1466 'cantrollback' => array(
1467 'code' => 'onlyauthor',
1468 'info' => "The page you tried to rollback only has one author"
1470 'readonlytext' => array(
1471 'code' => 'readonly',
1472 'info' => "The wiki is currently in read-only mode"
1474 'sessionfailure' => array(
1475 'code' => 'badtoken',
1476 'info' => "Invalid token" ),
1477 'cannotdelete' => array(
1478 'code' => 'cantdelete',
1479 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1481 'notanarticle' => array(
1482 'code' => 'missingtitle',
1483 'info' => "The page you requested doesn't exist"
1485 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1487 'immobile_namespace' => array(
1488 'code' => 'immobilenamespace',
1489 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1491 'articleexists' => array(
1492 'code' => 'articleexists',
1493 'info' => "The destination article already exists and is not a redirect to the source article"
1495 'protectedpage' => array(
1496 'code' => 'protectedpage',
1497 'info' => "You don't have permission to perform this move"
1499 'hookaborted' => array(
1500 'code' => 'hookaborted',
1501 'info' => "The modification you tried to make was aborted by an extension hook"
1503 'cantmove-titleprotected' => array(
1504 'code' => 'protectedtitle',
1505 'info' => "The destination article has been protected from creation"
1507 'imagenocrossnamespace' => array(
1508 'code' => 'nonfilenamespace',
1509 'info' => "Can't move a file to a non-file namespace"
1511 'imagetypemismatch' => array(
1512 'code' => 'filetypemismatch',
1513 'info' => "The new file extension doesn't match its type"
1515 // 'badarticleerror' => shouldn't happen
1516 // 'badtitletext' => shouldn't happen
1517 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1518 'range_block_disabled' => array(
1519 'code' => 'rangedisabled',
1520 'info' => "Blocking IP ranges has been disabled"
1522 'nosuchusershort' => array(
1523 'code' => 'nosuchuser',
1524 'info' => "The user you specified doesn't exist"
1526 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1527 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1528 'ipb_already_blocked' => array(
1529 'code' => 'alreadyblocked',
1530 'info' => "The user you tried to block was already blocked"
1532 'ipb_blocked_as_range' => array(
1533 'code' => 'blockedasrange',
1534 '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."
1536 'ipb_cant_unblock' => array(
1537 'code' => 'cantunblock',
1538 'info' => "The block you specified was not found. It may have been unblocked already"
1540 'mailnologin' => array(
1541 'code' => 'cantsend',
1542 '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"
1544 'ipbblocked' => array(
1545 'code' => 'ipbblocked',
1546 'info' => 'You cannot block or unblock users while you are yourself blocked'
1548 'ipbnounblockself' => array(
1549 'code' => 'ipbnounblockself',
1550 'info' => 'You are not allowed to unblock yourself'
1552 'usermaildisabled' => array(
1553 'code' => 'usermaildisabled',
1554 'info' => "User email has been disabled"
1556 'blockedemailuser' => array(
1557 'code' => 'blockedfrommail',
1558 'info' => "You have been blocked from sending email"
1560 'notarget' => array(
1561 'code' => 'notarget',
1562 'info' => "You have not specified a valid target for this action"
1565 'code' => 'noemail',
1566 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1568 'rcpatroldisabled' => array(
1569 'code' => 'patroldisabled',
1570 'info' => "Patrolling is disabled on this wiki"
1572 'markedaspatrollederror-noautopatrol' => array(
1573 'code' => 'noautopatrol',
1574 'info' => "You don't have permission to patrol your own changes"
1576 'delete-toobig' => array(
1577 'code' => 'bigdelete',
1578 'info' => "You can't delete this page because it has more than \$1 revisions"
1580 'movenotallowedfile' => array(
1581 'code' => 'cantmovefile',
1582 'info' => "You don't have permission to move files"
1584 'userrights-no-interwiki' => array(
1585 'code' => 'nointerwikiuserrights',
1586 'info' => "You don't have permission to change user rights on other wikis"
1588 'userrights-nodatabase' => array(
1589 'code' => 'nosuchdatabase',
1590 'info' => "Database \"\$1\" does not exist or is not local"
1592 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1593 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1594 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1595 'import-rootpage-invalid' => array(
1596 'code' => 'import-rootpage-invalid',
1597 'info' => 'Root page is an invalid title'
1599 'import-rootpage-nosubpage' => array(
1600 'code' => 'import-rootpage-nosubpage',
1601 'info' => 'Namespace "$1" of the root page does not allow subpages'
1604 // API-specific messages
1605 'readrequired' => array(
1606 'code' => 'readapidenied',
1607 'info' => "You need read permission to use this module"
1609 'writedisabled' => array(
1610 'code' => 'noapiwrite',
1611 '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"
1613 'writerequired' => array(
1614 'code' => 'writeapidenied',
1615 'info' => "You're not allowed to edit this wiki through the API"
1617 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1618 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1619 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1620 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1621 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1622 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1623 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1624 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1625 'create-titleexists' => array(
1626 'code' => 'create-titleexists',
1627 'info' => "Existing titles can't be protected with 'create'"
1629 'missingtitle-createonly' => array(
1630 'code' => 'missingtitle-createonly',
1631 'info' => "Missing titles can only be protected with 'create'"
1633 'cantblock' => array( 'code' => 'cantblock',
1634 'info' => "You don't have permission to block users"
1636 'canthide' => array(
1637 'code' => 'canthide',
1638 'info' => "You don't have permission to hide user names from the block log"
1640 'cantblock-email' => array(
1641 'code' => 'cantblock-email',
1642 'info' => "You don't have permission to block users from sending email through the wiki"
1644 'unblock-notarget' => array(
1645 'code' => 'notarget',
1646 'info' => "Either the id or the user parameter must be set"
1648 'unblock-idanduser' => array(
1649 'code' => 'idanduser',
1650 'info' => "The id and user parameters can't be used together"
1652 'cantunblock' => array(
1653 'code' => 'permissiondenied',
1654 'info' => "You don't have permission to unblock users"
1656 'cannotundelete' => array(
1657 'code' => 'cantundelete',
1658 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1660 'permdenied-undelete' => array(
1661 'code' => 'permissiondenied',
1662 'info' => "You don't have permission to restore deleted revisions"
1664 'createonly-exists' => array(
1665 'code' => 'articleexists',
1666 'info' => "The article you tried to create has been created already"
1668 'nocreate-missing' => array(
1669 'code' => 'missingtitle',
1670 'info' => "The article you tried to edit doesn't exist"
1672 'cantchangecontentmodel' => array(
1673 'code' => 'cantchangecontentmodel',
1674 'info' => "You don't have permission to change the content model of a page"
1676 'nosuchrcid' => array(
1677 'code' => 'nosuchrcid',
1678 'info' => "There is no change with rcid \"\$1\""
1680 'protect-invalidaction' => array(
1681 'code' => 'protect-invalidaction',
1682 'info' => "Invalid protection type \"\$1\""
1684 'protect-invalidlevel' => array(
1685 'code' => 'protect-invalidlevel',
1686 'info' => "Invalid protection level \"\$1\""
1688 'toofewexpiries' => array(
1689 'code' => 'toofewexpiries',
1690 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1692 'cantimport' => array(
1693 'code' => 'cantimport',
1694 'info' => "You don't have permission to import pages"
1696 'cantimport-upload' => array(
1697 'code' => 'cantimport-upload',
1698 'info' => "You don't have permission to import uploaded pages"
1700 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1701 'importuploaderrorsize' => array(
1702 'code' => 'filetoobig',
1703 'info' => 'The file you uploaded is bigger than the maximum upload size'
1705 'importuploaderrorpartial' => array(
1706 'code' => 'partialupload',
1707 'info' => 'The file was only partially uploaded'
1709 'importuploaderrortemp' => array(
1710 'code' => 'notempdir',
1711 'info' => 'The temporary upload directory is missing'
1713 'importcantopen' => array(
1714 'code' => 'cantopenfile',
1715 'info' => "Couldn't open the uploaded file"
1717 'import-noarticle' => array(
1718 'code' => 'badinterwiki',
1719 'info' => 'Invalid interwiki title specified'
1721 'importbadinterwiki' => array(
1722 'code' => 'badinterwiki',
1723 'info' => 'Invalid interwiki title specified'
1725 'import-unknownerror' => array(
1726 'code' => 'import-unknownerror',
1727 'info' => "Unknown error on import: \"\$1\""
1729 'cantoverwrite-sharedfile' => array(
1730 'code' => 'cantoverwrite-sharedfile',
1731 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1733 'sharedfile-exists' => array(
1734 'code' => 'fileexists-sharedrepo-perm',
1735 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1737 'mustbeposted' => array(
1738 'code' => 'mustbeposted',
1739 'info' => "The \$1 module requires a POST request"
1743 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1745 'specialpage-cantexecute' => array(
1746 'code' => 'specialpage-cantexecute',
1747 'info' => "You don't have permission to view the results of this special page"
1749 'invalidoldimage' => array(
1750 'code' => 'invalidoldimage',
1751 'info' => 'The oldimage parameter has invalid format'
1753 'nodeleteablefile' => array(
1754 'code' => 'nodeleteablefile',
1755 'info' => 'No such old version of the file'
1757 'fileexists-forbidden' => array(
1758 'code' => 'fileexists-forbidden',
1759 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1761 'fileexists-shared-forbidden' => array(
1762 'code' => 'fileexists-shared-forbidden',
1763 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1765 'filerevert-badversion' => array(
1766 'code' => 'filerevert-badversion',
1767 'info' => 'There is no previous local version of this file with the provided timestamp.'
1770 // ApiEditPage messages
1771 'noimageredirect-anon' => array(
1772 'code' => 'noimageredirect-anon',
1773 'info' => "Anonymous users can't create image redirects"
1775 'noimageredirect-logged' => array(
1776 'code' => 'noimageredirect',
1777 'info' => "You don't have permission to create image redirects"
1779 'spamdetected' => array(
1780 'code' => 'spamdetected',
1781 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1783 'contenttoobig' => array(
1784 'code' => 'contenttoobig',
1785 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1787 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1788 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1789 'wasdeleted' => array(
1790 'code' => 'pagedeleted',
1791 'info' => "The page has been deleted since you fetched its timestamp"
1793 'blankpage' => array(
1794 'code' => 'emptypage',
1795 'info' => "Creating new, empty pages is not allowed"
1797 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1798 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1799 'missingtext' => array(
1801 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1803 'emptynewsection' => array(
1804 'code' => 'emptynewsection',
1805 'info' => 'Creating empty new sections is not possible.'
1807 'revwrongpage' => array(
1808 'code' => 'revwrongpage',
1809 'info' => "r\$1 is not a revision of \"\$2\""
1811 'undo-failure' => array(
1812 'code' => 'undofailure',
1813 'info' => 'Undo failed due to conflicting intermediate edits'
1815 'content-not-allowed-here' => array(
1816 'code' => 'contentnotallowedhere',
1817 'info' => 'Content model "$1" is not allowed at title "$2"'
1820 // Messages from WikiPage::doEit()
1821 'edit-hook-aborted' => array(
1822 'code' => 'edit-hook-aborted',
1823 'info' => "Your edit was aborted by an ArticleSave hook"
1825 'edit-gone-missing' => array(
1826 'code' => 'edit-gone-missing',
1827 'info' => "The page you tried to edit doesn't seem to exist anymore"
1829 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1830 'edit-already-exists' => array(
1831 'code' => 'edit-already-exists',
1832 'info' => 'It seems the page you tried to create already exist'
1836 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1837 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1838 'uploaddisabled' => array(
1839 'code' => 'uploaddisabled',
1840 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1842 'copyuploaddisabled' => array(
1843 'code' => 'copyuploaddisabled',
1844 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1846 'copyuploadbaddomain' => array(
1847 'code' => 'copyuploadbaddomain',
1848 'info' => 'Uploads by URL are not allowed from this domain.'
1850 'copyuploadbadurl' => array(
1851 'code' => 'copyuploadbadurl',
1852 'info' => 'Upload not allowed from this URL.'
1855 'filename-tooshort' => array(
1856 'code' => 'filename-tooshort',
1857 'info' => 'The filename is too short'
1859 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1860 'illegal-filename' => array(
1861 'code' => 'illegal-filename',
1862 'info' => 'The filename is not allowed'
1864 'filetype-missing' => array(
1865 'code' => 'filetype-missing',
1866 'info' => 'The file is missing an extension'
1869 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1871 // @codingStandardsIgnoreEnd
1874 * Helper function for readonly errors
1876 public function dieReadOnly() {
1877 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1878 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1879 array( 'readonlyreason' => wfReadOnlyReason() ) );
1883 * Output the error message related to a certain array
1884 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1886 public function dieUsageMsg( $error ) {
1887 # most of the time we send a 1 element, so we might as well send it as
1888 # a string and make this an array here.
1889 if ( is_string( $error ) ) {
1890 $error = array( $error );
1892 $parsed = $this->parseMsg( $error );
1893 $this->dieUsage( $parsed['info'], $parsed['code'] );
1897 * Will only set a warning instead of failing if the global $wgDebugAPI
1898 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1899 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1902 public function dieUsageMsgOrDebug( $error ) {
1903 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1904 $this->dieUsageMsg( $error );
1907 if ( is_string( $error ) ) {
1908 $error = array( $error );
1910 $parsed = $this->parseMsg( $error );
1911 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1915 * Die with the $prefix.'badcontinue' error. This call is common enough to
1916 * make it into the base method.
1917 * @param bool $condition Will only die if this value is true
1920 protected function dieContinueUsageIf( $condition ) {
1923 'Invalid continue param. You should pass the original value returned by the previous query',
1929 * Return the error message related to a certain array
1930 * @param array $error Element of a getUserPermissionsErrors()-style array
1931 * @return array('code' => code, 'info' => info)
1933 public function parseMsg( $error ) {
1934 $error = (array)$error; // It seems strings sometimes make their way in here
1935 $key = array_shift( $error );
1937 // Check whether the error array was nested
1938 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1939 if ( is_array( $key ) ) {
1941 $key = array_shift( $error );
1944 if ( isset( self
::$messageMap[$key] ) ) {
1946 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1947 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1951 // If the key isn't present, throw an "unknown error"
1952 return $this->parseMsg( array( 'unknownerror', $key ) );
1956 * Internal code errors should be reported with this method
1957 * @param string $method Method or function name
1958 * @param string $message Error message
1959 * @throws MWException
1961 protected static function dieDebug( $method, $message ) {
1962 throw new MWException( "Internal error in $method: $message" );
1966 * Write logging information for API features to a debug log, for usage
1968 * @param string $feature Feature being used.
1970 protected function logFeatureUsage( $feature ) {
1971 $request = $this->getRequest();
1972 $s = '"' . addslashes( $feature ) . '"' .
1973 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1974 ' "' . $request->getIP() . '"' .
1975 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1976 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1977 wfDebugLog( 'api-feature-usage', $s, 'private' );
1982 /************************************************************************//**
1983 * @name Help message generation
1988 * Return the description message.
1990 * @return string|array|Message
1992 protected function getDescriptionMessage() {
1993 return "apihelp-{$this->getModulePath()}-description";
1997 * Get final module description, after hooks have had a chance to tweak it as
2000 * @since 1.25, returns Message[] rather than string[]
2003 public function getFinalDescription() {
2004 $desc = $this->getDescription();
2005 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2006 $desc = self
::escapeWikiText( $desc );
2007 if ( is_array( $desc ) ) {
2008 $desc = join( "\n", $desc );
2010 $desc = (string)$desc;
2013 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2014 $this->getModulePrefix(),
2015 $this->getModuleName(),
2016 $this->getModulePath(),
2018 if ( !$msg->exists() ) {
2019 $msg = $this->msg( 'api-help-fallback-description', $desc );
2021 $msgs = array( $msg );
2023 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2029 * Get final list of parameters, after hooks have had a chance to
2030 * tweak it as needed.
2032 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2033 * @return array|bool False on no parameters
2034 * @since 1.21 $flags param added
2036 public function getFinalParams( $flags = 0 ) {
2037 $params = $this->getAllowedParams( $flags );
2042 if ( $this->needsToken() ) {
2043 $params['token'] = array(
2044 ApiBase
::PARAM_TYPE
=> 'string',
2045 ApiBase
::PARAM_REQUIRED
=> true,
2046 ApiBase
::PARAM_HELP_MSG
=> array(
2047 'api-help-param-token',
2048 $this->needsToken(),
2050 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2053 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2059 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2062 * @since 1.25, returns array of Message[] rather than array of string[]
2063 * @return array Keys are parameter names, values are arrays of Message objects
2065 public function getFinalParamDescription() {
2066 $prefix = $this->getModulePrefix();
2067 $name = $this->getModuleName();
2068 $path = $this->getModulePath();
2070 $desc = $this->getParamDescription();
2071 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2076 $desc = self
::escapeWikiText( $desc );
2078 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2080 foreach ( $params as $param => $settings ) {
2081 if ( !is_array( $settings ) ) {
2082 $settings = array();
2085 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2086 if ( is_array( $d ) ) {
2087 // Special handling for prop parameters
2088 $d = array_map( function ( $line ) {
2089 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2090 $line = "\n;{$m[1]}:{$m[2]}";
2094 $d = join( ' ', $d );
2097 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2098 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2100 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2101 if ( !$msg->exists() ) {
2102 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2105 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2106 array( $prefix, $param, $name, $path ) );
2108 $this->dieDebug( __METHOD__
,
2109 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2111 $msgs[$param] = array( $msg );
2113 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2114 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2115 $this->dieDebug( __METHOD__
,
2116 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2118 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2119 $this->dieDebug( __METHOD__
,
2120 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2121 'ApiBase::PARAM_TYPE is an array' );
2124 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2125 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2126 if ( isset( $valueMsgs[$value] ) ) {
2127 $msg = $valueMsgs[$value];
2129 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2131 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2132 array( $prefix, $param, $name, $path, $value ) );
2134 $m = new ApiHelpParamValueMessage(
2136 array( $m->getKey(), 'api-help-param-no-description' ),
2139 $msgs[$param][] = $m->setContext( $this->getContext() );
2141 $this->dieDebug( __METHOD__
,
2142 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2147 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2148 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2149 $this->dieDebug( __METHOD__
,
2150 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2152 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2153 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2154 array( $prefix, $param, $name, $path ) );
2156 $msgs[$param][] = $m;
2158 $this->dieDebug( __METHOD__
,
2159 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2165 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2171 * Generates the list of flags for the help screen and for action=paraminfo
2173 * Corresponding messages: api-help-flag-deprecated,
2174 * api-help-flag-internal, api-help-flag-readrights,
2175 * api-help-flag-writerights, api-help-flag-mustbeposted
2179 protected function getHelpFlags() {
2182 if ( $this->isDeprecated() ) {
2183 $flags[] = 'deprecated';
2185 if ( $this->isInternal() ) {
2186 $flags[] = 'internal';
2188 if ( $this->isReadMode() ) {
2189 $flags[] = 'readrights';
2191 if ( $this->isWriteMode() ) {
2192 $flags[] = 'writerights';
2194 if ( $this->mustBePosted() ) {
2195 $flags[] = 'mustbeposted';
2202 * Called from ApiHelp before the pieces are joined together and returned.
2204 * This exists mainly for ApiMain to add the Permissions and Credits
2205 * sections. Other modules probably don't need it.
2207 * @param string[] &$help Array of help data
2208 * @param array $options Options passed to ApiHelp::getHelp
2210 public function modifyHelp( array &$help, array $options ) {
2215 /************************************************************************//**
2220 /// @deprecated since 1.24
2221 const PROP_ROOT
= 'ROOT';
2222 /// @deprecated since 1.24
2223 const PROP_LIST
= 'LIST';
2224 /// @deprecated since 1.24
2225 const PROP_TYPE
= 0;
2226 /// @deprecated since 1.24
2227 const PROP_NULLABLE
= 1;
2230 * Formerly returned a string that identifies the version of the extending
2231 * class. Typically included the class name, the svn revision, timestamp,
2232 * and last author. Usually done with SVN's Id keyword
2234 * @deprecated since 1.21, version string is no longer supported
2237 public function getVersion() {
2238 wfDeprecated( __METHOD__
, '1.21' );
2243 * Formerly used to fetch a list of possible properites in the result,
2244 * somehow organized with respect to the prop parameter that causes them to
2245 * be returned. The specific semantics of the return value was never
2246 * specified. Since this was never possible to be accurately updated, it
2249 * @deprecated since 1.24
2250 * @return array|bool
2252 protected function getResultProperties() {
2253 wfDeprecated( __METHOD__
, '1.24' );
2258 * @see self::getResultProperties()
2259 * @deprecated since 1.24
2260 * @return array|bool
2262 public function getFinalResultProperties() {
2263 wfDeprecated( __METHOD__
, '1.24' );
2268 * @see self::getResultProperties()
2269 * @deprecated since 1.24
2271 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2272 wfDeprecated( __METHOD__
, '1.24' );
2276 * @see self::getPossibleErrors()
2277 * @deprecated since 1.24
2280 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2281 wfDeprecated( __METHOD__
, '1.24' );
2286 * @see self::getPossibleErrors()
2287 * @deprecated since 1.24
2290 public function getRequireMaxOneParameterErrorMessages( $params ) {
2291 wfDeprecated( __METHOD__
, '1.24' );
2296 * @see self::getPossibleErrors()
2297 * @deprecated since 1.24
2300 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2301 wfDeprecated( __METHOD__
, '1.24' );
2306 * @see self::getPossibleErrors()
2307 * @deprecated since 1.24
2310 public function getTitleOrPageIdErrorMessage() {
2311 wfDeprecated( __METHOD__
, '1.24' );
2316 * This formerly attempted to return a list of all possible errors returned
2317 * by the module. However, this was impossible to maintain in many cases
2318 * since errors could come from other areas of MediaWiki and in some cases
2319 * from arbitrary extension hooks. Since a partial list claiming to be
2320 * comprehensive is unlikely to be useful, it was removed.
2322 * @deprecated since 1.24
2325 public function getPossibleErrors() {
2326 wfDeprecated( __METHOD__
, '1.24' );
2331 * @see self::getPossibleErrors()
2332 * @deprecated since 1.24
2335 public function getFinalPossibleErrors() {
2336 wfDeprecated( __METHOD__
, '1.24' );
2341 * @see self::getPossibleErrors()
2342 * @deprecated since 1.24
2345 public function parseErrors( $errors ) {
2346 wfDeprecated( __METHOD__
, '1.24' );
2351 * Returns the description string for this module
2353 * Ignored if an i18n message exists for
2354 * "apihelp-{$this->getModulePathString()}-description".
2356 * @deprecated since 1.25
2357 * @return Message|string|array
2359 protected function getDescription() {
2364 * Returns an array of parameter descriptions.
2366 * For each parameter, ignored if an i18n message exists for the parameter.
2367 * By default that message is
2368 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2369 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2370 * self::getFinalParams().
2372 * @deprecated since 1.25
2373 * @return array|bool False on no parameter descriptions
2375 protected function getParamDescription() {
2380 * Returns usage examples for this module.
2382 * Return value as an array is either:
2383 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2385 * - sequential numeric keys with even-numbered keys being display-text
2386 * and odd-numbered keys being partial urls
2387 * - partial URLs as keys with display-text (string or array-to-be-joined)
2389 * Return value as a string is the same as an array with a numeric key and
2390 * that value, and boolean false means "no examples".
2392 * @deprecated since 1.25, use getExamplesMessages() instead
2393 * @return bool|string|array
2395 protected function getExamples() {
2400 * Generates help message for this module, or false if there is no description
2401 * @deprecated since 1.25
2402 * @return string|bool
2404 public function makeHelpMsg() {
2405 wfDeprecated( __METHOD__
, '1.25' );
2406 static $lnPrfx = "\n ";
2408 $msg = $this->getFinalDescription();
2410 if ( $msg !== false ) {
2412 if ( !is_array( $msg ) ) {
2417 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2419 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2421 if ( $this->isReadMode() ) {
2422 $msg .= "\nThis module requires read rights";
2424 if ( $this->isWriteMode() ) {
2425 $msg .= "\nThis module requires write rights";
2427 if ( $this->mustBePosted() ) {
2428 $msg .= "\nThis module only accepts POST requests";
2430 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2431 $this->mustBePosted()
2437 $paramsMsg = $this->makeHelpMsgParameters();
2438 if ( $paramsMsg !== false ) {
2439 $msg .= "Parameters:\n$paramsMsg";
2442 $examples = $this->getExamples();
2444 if ( !is_array( $examples ) ) {
2449 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2450 foreach ( $examples as $k => $v ) {
2451 if ( is_numeric( $k ) ) {
2454 if ( is_array( $v ) ) {
2455 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2457 $msgExample = " $v";
2460 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2470 * @deprecated since 1.25
2471 * @param string $item
2474 private function indentExampleText( $item ) {
2479 * @deprecated since 1.25
2480 * @param string $prefix Text to split output items
2481 * @param string $title What is being output
2482 * @param string|array $input
2485 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2486 wfDeprecated( __METHOD__
, '1.25' );
2487 if ( $input === false ) {
2490 if ( !is_array( $input ) ) {
2491 $input = array( $input );
2494 if ( count( $input ) > 0 ) {
2496 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2500 $msg .= implode( $prefix, $input ) . "\n";
2509 * Generates the parameter descriptions for this module, to be displayed in the
2511 * @deprecated since 1.25
2512 * @return string|bool
2514 public function makeHelpMsgParameters() {
2515 wfDeprecated( __METHOD__
, '1.25' );
2516 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2519 $paramsDescription = $this->getFinalParamDescription();
2521 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2522 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2523 foreach ( $params as $paramName => $paramSettings ) {
2524 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2525 if ( is_array( $desc ) ) {
2526 $desc = implode( $paramPrefix, $desc );
2530 if ( !is_array( $paramSettings ) ) {
2531 $paramSettings = array(
2532 self
::PARAM_DFLT
=> $paramSettings,
2536 //handle missing type
2537 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2538 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2539 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2541 if ( is_bool( $dflt ) ) {
2542 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2543 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2544 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2545 } elseif ( is_int( $dflt ) ) {
2546 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2550 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2551 && $paramSettings[self
::PARAM_DEPRECATED
]
2553 $desc = "DEPRECATED! $desc";
2556 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2557 && $paramSettings[self
::PARAM_REQUIRED
]
2559 $desc .= $paramPrefix . "This parameter is required";
2562 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2563 ?
$paramSettings[self
::PARAM_TYPE
]
2565 if ( isset( $type ) ) {
2566 $hintPipeSeparated = true;
2567 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2568 ?
$paramSettings[self
::PARAM_ISMULTI
]
2571 $prompt = 'Values (separate with \'|\'): ';
2573 $prompt = 'One value: ';
2576 if ( $type === 'submodule' ) {
2577 $type = $this->getModuleManager()->getNames( $paramName );
2580 if ( is_array( $type ) ) {
2582 $nothingPrompt = '';
2583 foreach ( $type as $t ) {
2585 $nothingPrompt = 'Can be empty, or ';
2590 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2591 $choicesstring = implode( ', ', $choices );
2592 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2593 $hintPipeSeparated = false;
2597 // Special handling because namespaces are
2598 // type-limited, yet they are not given
2599 $desc .= $paramPrefix . $prompt;
2600 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2601 100, $descWordwrap );
2602 $hintPipeSeparated = false;
2605 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2606 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2607 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2609 $desc .= ' allowed';
2612 $s = $multi ?
's' : '';
2613 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2614 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2615 if ( $hasMin ||
$hasMax ) {
2617 $intRangeStr = "The value$s must be no less than " .
2618 "{$paramSettings[self::PARAM_MIN]}";
2619 } elseif ( !$hasMin ) {
2620 $intRangeStr = "The value$s must be no more than " .
2621 "{$paramSettings[self::PARAM_MAX]}";
2623 $intRangeStr = "The value$s must be between " .
2624 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2627 $desc .= $paramPrefix . $intRangeStr;
2631 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2637 if ( $hintPipeSeparated ) {
2638 $desc .= $paramPrefix . "Separate values with '|'";
2641 $isArray = is_array( $type );
2643 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2645 $desc .= $paramPrefix . "Maximum number of values " .
2646 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2651 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2652 if ( !is_null( $default ) && $default !== false ) {
2653 $desc .= $paramPrefix . "Default: $default";
2656 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2666 * @deprecated since 1.25, always returns empty string
2667 * @param DatabaseBase|bool $db
2670 public function getModuleProfileName( $db = false ) {
2671 wfDeprecated( __METHOD__
, '1.25' );
2676 * @deprecated since 1.25
2678 public function profileIn() {
2679 // No wfDeprecated() yet because extensions call this and might need to
2680 // keep doing so for BC.
2684 * @deprecated since 1.25
2686 public function profileOut() {
2687 // No wfDeprecated() yet because extensions call this and might need to
2688 // keep doing so for BC.
2692 * @deprecated since 1.25
2694 public function safeProfileOut() {
2695 wfDeprecated( __METHOD__
, '1.25' );
2699 * @deprecated since 1.25, always returns 0
2702 public function getProfileTime() {
2703 wfDeprecated( __METHOD__
, '1.25' );
2708 * @deprecated since 1.25
2710 public function profileDBIn() {
2711 wfDeprecated( __METHOD__
, '1.25' );
2715 * @deprecated since 1.25
2717 public function profileDBOut() {
2718 wfDeprecated( __METHOD__
, '1.25' );
2722 * @deprecated since 1.25, always returns 0
2725 public function getProfileDBTime() {
2726 wfDeprecated( __METHOD__
, '1.25' );
2731 * Get the result data array (read-only)
2732 * @deprecated since 1.25, use $this->getResult() methods instead
2735 public function getResultData() {
2736 return $this->getResult()->getData();
2743 * For really cool vim folding this needs to be at the end:
2744 * vim: foldmarker=@{,@} foldmethod=marker