5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Specify an alternative i18n message for this help parameter.
69 // Value is $msg for ApiBase::makeMessage()
70 const PARAM_HELP_MSG
= 10;
72 // Specify additional i18n messages to append to the normal message. Value
73 // is an array of $msg for ApiBase::makeMessage()
74 const PARAM_HELP_MSG_APPEND
= 11;
76 // Specify additional information tags for the parameter. Value is an array
77 // of arrays, with the first member being the 'tag' for the info and the
78 // remaining members being the values. In the help, this is formatted using
79 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
80 // comma-joined list of values, $3 = module prefix.
81 const PARAM_HELP_MSG_INFO
= 12;
83 // When PARAM_TYPE is an array, this may be an array mapping those values
84 // to page titles which will be linked in the help.
85 const PARAM_VALUE_LINKS
= 13;
87 // When PARAM_TYPE is an array, this is an array mapping those values to
88 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
89 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
90 const PARAM_HELP_MSG_PER_VALUE
= 14;
92 const LIMIT_BIG1
= 500; // Fast query, std user limit
93 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
94 const LIMIT_SML1
= 50; // Slow query, std user limit
95 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
98 * getAllowedParams() flag: When set, the result could take longer to generate,
99 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
102 const GET_VALUES_FOR_HELP
= 1;
105 private $mMainModule;
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
112 * @param ApiMain $mainModule
113 * @param string $moduleName Name of this module
114 * @param string $modulePrefix Prefix to use for parameter names
116 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
117 $this->mMainModule
= $mainModule;
118 $this->mModuleName
= $moduleName;
119 $this->mModulePrefix
= $modulePrefix;
121 if ( !$this->isMain() ) {
122 $this->setContext( $mainModule->getContext() );
127 /************************************************************************//**
128 * @name Methods to implement
133 * Evaluates the parameters, performs the requested query, and sets up
134 * the result. Concrete implementations of ApiBase must override this
135 * method to provide whatever functionality their module offers.
136 * Implementations must not produce any output on their own and are not
137 * expected to handle any errors.
139 * The execute() method will be invoked directly by ApiMain immediately
140 * before the result of the module is output. Aside from the
141 * constructor, implementations should assume that no other methods
142 * will be called externally on the module before the result is
145 * The result data should be stored in the ApiResult object available
146 * through getResult().
148 abstract public function execute();
151 * Get the module manager, or null if this module has no sub-modules
153 * @return ApiModuleManager
155 public function getModuleManager() {
160 * If the module may only be used with a certain format module,
161 * it should override this method to return an instance of that formatter.
162 * A value of null means the default format will be used.
163 * @return mixed Instance of a derived class of ApiFormatBase, or null
165 public function getCustomPrinter() {
170 * Returns usage examples for this module.
172 * Return value has query strings as keys, with values being either strings
173 * (message key), arrays (message key + parameter), or Message objects.
175 * Do not call this base class implementation when overriding this method.
180 protected function getExamplesMessages() {
181 // Fall back to old non-localised method
184 $examples = $this->getExamples();
186 if ( !is_array( $examples ) ) {
187 $examples = array( $examples );
188 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
189 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
190 !preg_match( '/^\s*api\.php\?/', $examples[0] )
192 // Fix up the ugly "even numbered elements are description, odd
193 // numbered elemts are the link" format (see doc for self::getExamples)
195 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
196 $tmp[$examples[$i +
1]] = $examples[$i];
201 foreach ( $examples as $k => $v ) {
202 if ( is_numeric( $k ) ) {
207 $msg = self
::escapeWikiText( $v );
208 if ( is_array( $msg ) ) {
209 $msg = join( " ", $msg );
213 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
214 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
222 * Return links to more detailed help pages about the module.
223 * @since 1.25, returning boolean false is deprecated
224 * @return string|array
226 public function getHelpUrls() {
231 * Returns an array of allowed parameters (parameter name) => (default
232 * value) or (parameter name) => (array with PARAM_* constants as keys)
233 * Don't call this function directly: use getFinalParams() to allow
234 * hooks to modify parameters as needed.
236 * Some derived classes may choose to handle an integer $flags parameter
237 * in the overriding methods. Callers of this method can pass zero or
238 * more OR-ed flags like GET_VALUES_FOR_HELP.
242 protected function getAllowedParams( /* $flags = 0 */ ) {
243 // int $flags is not declared because it causes "Strict standards"
244 // warning. Most derived classes do not implement it.
249 * Indicates if this module needs maxlag to be checked
252 public function shouldCheckMaxlag() {
257 * Indicates whether this module requires read rights
260 public function isReadMode() {
265 * Indicates whether this module requires write mode
268 public function isWriteMode() {
273 * Indicates whether this module must be called with a POST request
276 public function mustBePosted() {
277 return $this->needsToken() !== false;
281 * Indicates whether this module is deprecated
285 public function isDeprecated() {
290 * Indicates whether this module is "internal"
291 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
295 public function isInternal() {
300 * Returns the token type this module requires in order to execute.
302 * Modules are strongly encouraged to use the core 'csrf' type unless they
303 * have specialized security needs. If the token type is not one of the
304 * core types, you must use the ApiQueryTokensRegisterTypes hook to
307 * Returning a non-falsey value here will force the addition of an
308 * appropriate 'token' parameter in self::getFinalParams(). Also,
309 * self::mustBePosted() must return true when tokens are used.
311 * In previous versions of MediaWiki, true was a valid return value.
312 * Returning true will generate errors indicating that the API module needs
315 * @return string|false
317 public function needsToken() {
322 * Fetch the salt used in the Web UI corresponding to this module.
324 * Only override this if the Web UI uses a token with a non-constant salt.
327 * @param array $params All supplied parameters for the module
328 * @return string|array|null
330 protected function getWebUITokenSalt( array $params ) {
336 /************************************************************************//**
337 * @name Data access methods
342 * Get the name of the module being executed by this instance
345 public function getModuleName() {
346 return $this->mModuleName
;
350 * Get parameter prefix (usually two letters or an empty string).
353 public function getModulePrefix() {
354 return $this->mModulePrefix
;
358 * Get the main module
361 public function getMain() {
362 return $this->mMainModule
;
366 * Returns true if this module is the main module ($this === $this->mMainModule),
370 public function isMain() {
371 return $this === $this->mMainModule
;
375 * Get the parent of this module
377 * @return ApiBase|null
379 public function getParent() {
380 return $this->isMain() ?
null : $this->getMain();
384 * Get the path to this module
389 public function getModulePath() {
390 if ( $this->isMain() ) {
392 } elseif ( $this->getParent()->isMain() ) {
393 return $this->getModuleName();
395 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
400 * Get a module from its module path
403 * @param string $path
404 * @return ApiBase|null
405 * @throws UsageException
407 public function getModuleFromPath( $path ) {
408 $module = $this->getMain();
409 if ( $path === 'main' ) {
413 $parts = explode( '+', $path );
414 if ( count( $parts ) === 1 ) {
415 // In case the '+' was typed into URL, it resolves as a space
416 $parts = explode( ' ', $path );
419 $count = count( $parts );
420 for ( $i = 0; $i < $count; $i++
) {
422 $manager = $parent->getModuleManager();
423 if ( $manager === null ) {
424 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
425 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
427 $module = $manager->getModule( $parts[$i] );
429 if ( $module === null ) {
430 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
432 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
442 * Get the result object
445 public function getResult() {
446 // Main module has getResult() method overridden
447 // Safety - avoid infinite loop:
448 if ( $this->isMain() ) {
449 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
452 return $this->getMain()->getResult();
456 * Get the result data array (read-only)
459 public function getResultData() {
460 return $this->getResult()->getData();
464 * Gets a default slave database connection object
465 * @return DatabaseBase
467 protected function getDB() {
468 if ( !isset( $this->mSlaveDB
) ) {
469 $this->profileDBIn();
470 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
471 $this->profileDBOut();
474 return $this->mSlaveDB
;
479 /************************************************************************//**
480 * @name Parameter handling
485 * This method mangles parameter name based on the prefix supplied to the constructor.
486 * Override this method to change parameter name during runtime
487 * @param string $paramName Parameter name
488 * @return string Prefixed parameter name
490 public function encodeParamName( $paramName ) {
491 return $this->mModulePrefix
. $paramName;
495 * Using getAllowedParams(), this function makes an array of the values
496 * provided by the user, with key being the name of the variable, and
497 * value - validated value from user or default. limits will not be
498 * parsed if $parseLimit is set to false; use this when the max
499 * limit is not definitive yet, e.g. when getting revisions.
500 * @param bool $parseLimit True by default
503 public function extractRequestParams( $parseLimit = true ) {
504 // Cache parameters, for performance and to avoid bug 24564.
505 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
506 $params = $this->getFinalParams();
509 if ( $params ) { // getFinalParams() can return false
510 foreach ( $params as $paramName => $paramSettings ) {
511 $results[$paramName] = $this->getParameterFromSettings(
512 $paramName, $paramSettings, $parseLimit );
515 $this->mParamCache
[$parseLimit] = $results;
518 return $this->mParamCache
[$parseLimit];
522 * Get a value for the given parameter
523 * @param string $paramName Parameter name
524 * @param bool $parseLimit See extractRequestParams()
525 * @return mixed Parameter value
527 protected function getParameter( $paramName, $parseLimit = true ) {
528 $params = $this->getFinalParams();
529 $paramSettings = $params[$paramName];
531 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
535 * Die if none or more than one of a certain set of parameters is set and not false.
537 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
538 * @param string $required,... Names of parameters of which exactly one must be set
540 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
541 $required = func_get_args();
542 array_shift( $required );
543 $p = $this->getModulePrefix();
545 $intersection = array_intersect( array_keys( array_filter( $params,
546 array( $this, "parameterNotEmpty" ) ) ), $required );
548 if ( count( $intersection ) > 1 ) {
550 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
552 } elseif ( count( $intersection ) == 0 ) {
554 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
561 * Die if more than one of a certain set of parameters is set and not false.
563 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
564 * @param string $required,... Names of parameters of which at most one must be set
566 public function requireMaxOneParameter( $params, $required /*...*/ ) {
567 $required = func_get_args();
568 array_shift( $required );
569 $p = $this->getModulePrefix();
571 $intersection = array_intersect( array_keys( array_filter( $params,
572 array( $this, "parameterNotEmpty" ) ) ), $required );
574 if ( count( $intersection ) > 1 ) {
576 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
583 * Die if none of a certain set of parameters is set and not false.
586 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
587 * @param string $required,... Names of parameters of which at least one must be set
589 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
590 $required = func_get_args();
591 array_shift( $required );
592 $p = $this->getModulePrefix();
594 $intersection = array_intersect(
595 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
599 if ( count( $intersection ) == 0 ) {
600 $this->dieUsage( "At least one of the parameters {$p}" .
601 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
606 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
608 * @param object $x Parameter to check is not null/false
611 private function parameterNotEmpty( $x ) {
612 return !is_null( $x ) && $x !== false;
616 * Get a WikiPage object from a title or pageid param, if possible.
617 * Can die, if no param is set or if the title or page id is not valid.
619 * @param array $params
620 * @param bool|string $load Whether load the object's state from the database:
621 * - false: don't load (if the pageid is given, it will still be loaded)
622 * - 'fromdb': load from a slave database
623 * - 'fromdbmaster': load from the master database
626 public function getTitleOrPageId( $params, $load = false ) {
627 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
630 if ( isset( $params['title'] ) ) {
631 $titleObj = Title
::newFromText( $params['title'] );
632 if ( !$titleObj ||
$titleObj->isExternal() ) {
633 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
635 if ( !$titleObj->canExist() ) {
636 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
638 $pageObj = WikiPage
::factory( $titleObj );
639 if ( $load !== false ) {
640 $pageObj->loadPageData( $load );
642 } elseif ( isset( $params['pageid'] ) ) {
643 if ( $load === false ) {
646 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
648 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
656 * Return true if we're to watch the page, false if not, null if no change.
657 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
658 * @param Title $titleObj The page under consideration
659 * @param string $userOption The user option to consider when $watchlist=preferences.
660 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
663 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
665 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
667 switch ( $watchlist ) {
675 # If the user is already watching, don't bother checking
676 if ( $userWatching ) {
679 # If no user option was passed, use watchdefault and watchcreations
680 if ( is_null( $userOption ) ) {
681 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
682 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
685 # Watch the article based on the user preference
686 return $this->getUser()->getBoolOption( $userOption );
689 return $userWatching;
692 return $userWatching;
697 * Using the settings determine the value for the given parameter
699 * @param string $paramName Parameter name
700 * @param array|mixed $paramSettings Default value or an array of settings
701 * using PARAM_* constants.
702 * @param bool $parseLimit Parse limit?
703 * @return mixed Parameter value
705 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
706 // Some classes may decide to change parameter names
707 $encParamName = $this->encodeParamName( $paramName );
709 if ( !is_array( $paramSettings ) ) {
710 $default = $paramSettings;
712 $type = gettype( $paramSettings );
717 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
718 ?
$paramSettings[self
::PARAM_DFLT
]
720 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
721 ?
$paramSettings[self
::PARAM_ISMULTI
]
723 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
724 ?
$paramSettings[self
::PARAM_TYPE
]
726 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
727 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
729 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
730 ?
$paramSettings[self
::PARAM_DEPRECATED
]
732 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
733 ?
$paramSettings[self
::PARAM_REQUIRED
]
736 // When type is not given, and no choices, the type is the same as $default
737 if ( !isset( $type ) ) {
738 if ( isset( $default ) ) {
739 $type = gettype( $default );
741 $type = 'NULL'; // allow everything
746 if ( $type == 'boolean' ) {
747 if ( isset( $default ) && $default !== false ) {
748 // Having a default value of anything other than 'false' is not allowed
751 "Boolean param $encParamName's default is set to '$default'. " .
752 "Boolean parameters must default to false."
756 $value = $this->getMain()->getCheck( $encParamName );
757 } elseif ( $type == 'upload' ) {
758 if ( isset( $default ) ) {
759 // Having a default value is not allowed
762 "File upload param $encParamName's default is set to " .
763 "'$default'. File upload parameters may not have a default." );
766 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
768 $value = $this->getMain()->getUpload( $encParamName );
769 if ( !$value->exists() ) {
770 // This will get the value without trying to normalize it
771 // (because trying to normalize a large binary file
772 // accidentally uploaded as a field fails spectacularly)
773 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
774 if ( $value !== null ) {
776 "File upload param $encParamName is not a file upload; " .
777 "be sure to use multipart/form-data for your POST and include " .
778 "a filename in the Content-Disposition header.",
779 "badupload_{$encParamName}"
784 $value = $this->getMain()->getVal( $encParamName, $default );
786 if ( isset( $value ) && $type == 'namespace' ) {
787 $type = MWNamespace
::getValidNamespaces();
789 if ( isset( $value ) && $type == 'submodule' ) {
790 $type = $this->getModuleManager()->getNames( $paramName );
794 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
795 $value = $this->parseMultiValue(
799 is_array( $type ) ?
$type : null
803 // More validation only when choices were not given
804 // choices were validated in parseMultiValue()
805 if ( isset( $value ) ) {
806 if ( !is_array( $type ) ) {
808 case 'NULL': // nothing to do
811 if ( $required && $value === '' ) {
812 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
815 case 'integer': // Force everything using intval() and optionally validate limits
816 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
817 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
818 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
819 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
821 if ( is_array( $value ) ) {
822 $value = array_map( 'intval', $value );
823 if ( !is_null( $min ) ||
!is_null( $max ) ) {
824 foreach ( $value as &$v ) {
825 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
829 $value = intval( $value );
830 if ( !is_null( $min ) ||
!is_null( $max ) ) {
831 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
836 if ( !$parseLimit ) {
837 // Don't do any validation whatsoever
840 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
841 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
845 "MAX1 or MAX2 are not defined for the limit $encParamName"
849 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
851 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
852 if ( $value == 'max' ) {
853 $value = $this->getMain()->canApiHighLimits()
854 ?
$paramSettings[self
::PARAM_MAX2
]
855 : $paramSettings[self
::PARAM_MAX
];
856 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
858 $value = intval( $value );
859 $this->validateLimit(
863 $paramSettings[self
::PARAM_MAX
],
864 $paramSettings[self
::PARAM_MAX2
]
870 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
874 if ( is_array( $value ) ) {
875 foreach ( $value as $key => $val ) {
876 $value[$key] = $this->validateTimestamp( $val, $encParamName );
879 $value = $this->validateTimestamp( $value, $encParamName );
883 if ( is_array( $value ) ) {
884 foreach ( $value as $key => $val ) {
885 $value[$key] = $this->validateUser( $val, $encParamName );
888 $value = $this->validateUser( $value, $encParamName );
891 case 'upload': // nothing to do
894 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
898 // Throw out duplicates if requested
899 if ( !$dupes && is_array( $value ) ) {
900 $value = array_unique( $value );
903 // Set a warning if a deprecated parameter has been passed
904 if ( $deprecated && $value !== false ) {
905 $this->setWarning( "The $encParamName parameter has been deprecated." );
907 } elseif ( $required ) {
908 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
915 * Return an array of values that were given in a 'a|b|c' notation,
916 * after it optionally validates them against the list allowed values.
918 * @param string $valueName The name of the parameter (for error
920 * @param mixed $value The value being parsed
921 * @param bool $allowMultiple Can $value contain more than one value
923 * @param string[]|null $allowedValues An array of values to check against. If
924 * null, all values are accepted.
925 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
927 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
928 if ( trim( $value ) === '' && $allowMultiple ) {
932 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
933 // because it unstubs $wgUser
934 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
935 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
939 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
940 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
941 "the limit is $sizeLimit" );
944 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
945 // Bug 33482 - Allow entries with | in them for non-multiple values
946 if ( in_array( $value, $allowedValues, true ) ) {
950 $possibleValues = is_array( $allowedValues )
951 ?
"of '" . implode( "', '", $allowedValues ) . "'"
954 "Only one $possibleValues is allowed for parameter '$valueName'",
955 "multival_$valueName"
959 if ( is_array( $allowedValues ) ) {
960 // Check for unknown values
961 $unknown = array_diff( $valuesList, $allowedValues );
962 if ( count( $unknown ) ) {
963 if ( $allowMultiple ) {
964 $s = count( $unknown ) > 1 ?
's' : '';
965 $vals = implode( ", ", $unknown );
966 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
969 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
974 // Now throw them out
975 $valuesList = array_intersect( $valuesList, $allowedValues );
978 return $allowMultiple ?
$valuesList : $valuesList[0];
982 * Validate the value against the minimum and user/bot maximum limits.
983 * Prints usage info on failure.
984 * @param string $paramName Parameter name
985 * @param int $value Parameter value
986 * @param int|null $min Minimum value
987 * @param int|null $max Maximum value for users
988 * @param int $botMax Maximum value for sysops/bots
989 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
991 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
992 if ( !is_null( $min ) && $value < $min ) {
994 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
995 $this->warnOrDie( $msg, $enforceLimits );
999 // Minimum is always validated, whereas maximum is checked only if not
1000 // running in internal call mode
1001 if ( $this->getMain()->isInternalMode() ) {
1005 // Optimization: do not check user's bot status unless really needed -- skips db query
1006 // assumes $botMax >= $max
1007 if ( !is_null( $max ) && $value > $max ) {
1008 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1009 if ( $value > $botMax ) {
1010 $msg = $this->encodeParamName( $paramName ) .
1011 " may not be over $botMax (set to $value) for bots or sysops";
1012 $this->warnOrDie( $msg, $enforceLimits );
1016 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1017 $this->warnOrDie( $msg, $enforceLimits );
1024 * Validate and normalize of parameters of type 'timestamp'
1025 * @param string $value Parameter value
1026 * @param string $encParamName Parameter name
1027 * @return string Validated and normalized parameter
1029 protected function validateTimestamp( $value, $encParamName ) {
1030 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1031 if ( $unixTimestamp === false ) {
1033 "Invalid value '$value' for timestamp parameter $encParamName",
1034 "badtimestamp_{$encParamName}"
1038 return wfTimestamp( TS_MW
, $unixTimestamp );
1042 * Validate the supplied token.
1045 * @param string $token Supplied token
1046 * @param array $params All supplied parameters for the module
1049 final public function validateToken( $token, array $params ) {
1050 $tokenType = $this->needsToken();
1051 $salts = ApiQueryTokens
::getTokenTypeSalts();
1052 if ( !isset( $salts[$tokenType] ) ) {
1053 throw new MWException(
1054 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1055 'without registering it'
1059 if ( $this->getUser()->matchEditToken(
1067 $webUiSalt = $this->getWebUITokenSalt( $params );
1068 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1080 * Validate and normalize of parameters of type 'user'
1081 * @param string $value Parameter value
1082 * @param string $encParamName Parameter name
1083 * @return string Validated and normalized parameter
1085 private function validateUser( $value, $encParamName ) {
1086 $title = Title
::makeTitleSafe( NS_USER
, $value );
1087 if ( $title === null ) {
1089 "Invalid value '$value' for user parameter $encParamName",
1090 "baduser_{$encParamName}"
1094 return $title->getText();
1099 /************************************************************************//**
1100 * @name Utility methods
1105 * Set a watch (or unwatch) based the based on a watchlist parameter.
1106 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1107 * @param Title $titleObj The article's title to change
1108 * @param string $userOption The user option to consider when $watch=preferences
1110 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1111 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1112 if ( $value === null ) {
1116 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1120 * Truncate an array to a certain length.
1121 * @param array $arr Array to truncate
1122 * @param int $limit Maximum length
1123 * @return bool True if the array was truncated, false otherwise
1125 public static function truncateArray( &$arr, $limit ) {
1127 while ( count( $arr ) > $limit ) {
1136 * Gets the user for whom to get the watchlist
1138 * @param array $params
1141 public function getWatchlistUser( $params ) {
1142 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1143 $user = User
::newFromName( $params['owner'], false );
1144 if ( !( $user && $user->getId() ) ) {
1145 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1147 $token = $user->getOption( 'watchlisttoken' );
1148 if ( $token == '' ||
$token != $params['token'] ) {
1150 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1155 if ( !$this->getUser()->isLoggedIn() ) {
1156 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1158 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1159 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1161 $user = $this->getUser();
1168 * A subset of wfEscapeWikiText for BC texts
1171 * @param string|array $v
1172 * @return string|array
1174 private static function escapeWikiText( $v ) {
1175 if ( is_array( $v ) ) {
1176 return array_map( 'self::escapeWikiText', $v );
1178 return strtr( $v, array(
1179 '__' => '__', '{' => '{', '}' => '}',
1180 '[[Category:' => '[[:Category:',
1181 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1187 * Create a Message from a string or array
1189 * A string is used as a message key. An array has the message key as the
1190 * first value and message parameters as subsequent values.
1193 * @param string|array|Message $msg
1194 * @param IContextSource $context
1195 * @param array $params
1196 * @return Message|null
1198 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1199 if ( is_string( $msg ) ) {
1200 $msg = wfMessage( $msg );
1201 } elseif ( is_array( $msg ) ) {
1202 $msg = call_user_func_array( 'wfMessage', $msg );
1204 if ( !$msg instanceof Message
) {
1208 $msg->setContext( $context );
1210 $msg->params( $params );
1218 /************************************************************************//**
1219 * @name Warning and error reporting
1224 * Set warning section for this module. Users should monitor this
1225 * section to notice any changes in API. Multiple calls to this
1226 * function will result in the warning messages being separated by
1228 * @param string $warning Warning message
1230 public function setWarning( $warning ) {
1231 $result = $this->getResult();
1232 $data = $result->getData();
1233 $moduleName = $this->getModuleName();
1234 if ( isset( $data['warnings'][$moduleName] ) ) {
1235 // Don't add duplicate warnings
1236 $oldWarning = $data['warnings'][$moduleName]['*'];
1237 $warnPos = strpos( $oldWarning, $warning );
1238 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1239 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1240 // Check if $warning is followed by "\n" or the end of the $oldWarning
1241 $warnPos +
= strlen( $warning );
1242 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1246 // If there is a warning already, append it to the existing one
1247 $warning = "$oldWarning\n$warning";
1250 ApiResult
::setContent( $msg, $warning );
1251 $result->addValue( 'warnings', $moduleName,
1252 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1256 * Adds a warning to the output, else dies
1258 * @param string $msg Message to show as a warning, or error message if dying
1259 * @param bool $enforceLimits Whether this is an enforce (die)
1261 private function warnOrDie( $msg, $enforceLimits = false ) {
1262 if ( $enforceLimits ) {
1263 $this->dieUsage( $msg, 'integeroutofrange' );
1266 $this->setWarning( $msg );
1270 * Throw a UsageException, which will (if uncaught) call the main module's
1271 * error handler and die with an error message.
1273 * @param string $description One-line human-readable description of the
1274 * error condition, e.g., "The API requires a valid action parameter"
1275 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1276 * automated identification of the error, e.g., 'unknown_action'
1277 * @param int $httpRespCode HTTP response code
1278 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1279 * @throws UsageException
1281 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1282 Profiler
::instance()->close();
1283 throw new UsageException(
1285 $this->encodeParamName( $errorCode ),
1292 * Get error (as code, string) from a Status object.
1295 * @param Status $status
1296 * @return array Array of code and error string
1298 public function getErrorFromStatus( $status ) {
1299 if ( $status->isGood() ) {
1300 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1303 $errors = $status->getErrorsArray();
1305 // No errors? Assume the warnings should be treated as errors
1306 $errors = $status->getWarningsArray();
1309 // Still no errors? Punt
1310 $errors = array( array( 'unknownerror-nocode' ) );
1313 // Cannot use dieUsageMsg() because extensions might return custom
1315 if ( $errors[0] instanceof Message
) {
1317 $code = $msg->getKey();
1319 $code = array_shift( $errors[0] );
1320 $msg = wfMessage( $code, $errors[0] );
1322 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1323 // Translate message to code, for backwards compatibility
1324 $code = ApiBase
::$messageMap[$code]['code'];
1327 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1331 * Throw a UsageException based on the errors in the Status object.
1334 * @param Status $status
1335 * @throws MWException
1337 public function dieStatus( $status ) {
1339 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1340 $this->dieUsage( $msg, $code );
1343 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1345 * Array that maps message keys to error messages. $1 and friends are replaced.
1347 public static $messageMap = array(
1348 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1349 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1350 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1352 // Messages from Title::getUserPermissionsErrors()
1353 'ns-specialprotected' => array(
1354 'code' => 'unsupportednamespace',
1355 'info' => "Pages in the Special namespace can't be edited"
1357 'protectedinterface' => array(
1358 'code' => 'protectednamespace-interface',
1359 'info' => "You're not allowed to edit interface messages"
1361 'namespaceprotected' => array(
1362 'code' => 'protectednamespace',
1363 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1365 'customcssprotected' => array(
1366 'code' => 'customcssprotected',
1367 'info' => "You're not allowed to edit custom CSS pages"
1369 'customjsprotected' => array(
1370 'code' => 'customjsprotected',
1371 'info' => "You're not allowed to edit custom JavaScript pages"
1373 'cascadeprotected' => array(
1374 'code' => 'cascadeprotected',
1375 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1377 'protectedpagetext' => array(
1378 'code' => 'protectedpage',
1379 'info' => "The \"\$1\" right is required to edit this page"
1381 'protect-cantedit' => array(
1382 'code' => 'cantedit',
1383 'info' => "You can't protect this page because you can't edit it"
1385 'deleteprotected' => array(
1386 'code' => 'cantedit',
1387 'info' => "You can't delete this page because it has been protected"
1389 'badaccess-group0' => array(
1390 'code' => 'permissiondenied',
1391 'info' => "Permission denied"
1392 ), // Generic permission denied message
1393 'badaccess-groups' => array(
1394 'code' => 'permissiondenied',
1395 'info' => "Permission denied"
1397 'titleprotected' => array(
1398 'code' => 'protectedtitle',
1399 'info' => "This title has been protected from creation"
1401 'nocreate-loggedin' => array(
1402 'code' => 'cantcreate',
1403 'info' => "You don't have permission to create new pages"
1405 'nocreatetext' => array(
1406 'code' => 'cantcreate-anon',
1407 'info' => "Anonymous users can't create new pages"
1409 'movenologintext' => array(
1410 'code' => 'cantmove-anon',
1411 'info' => "Anonymous users can't move pages"
1413 'movenotallowed' => array(
1414 'code' => 'cantmove',
1415 'info' => "You don't have permission to move pages"
1417 'confirmedittext' => array(
1418 'code' => 'confirmemail',
1419 'info' => "You must confirm your email address before you can edit"
1421 'blockedtext' => array(
1422 'code' => 'blocked',
1423 'info' => "You have been blocked from editing"
1425 'autoblockedtext' => array(
1426 'code' => 'autoblocked',
1427 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1430 // Miscellaneous interface messages
1431 'actionthrottledtext' => array(
1432 'code' => 'ratelimited',
1433 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1435 'alreadyrolled' => array(
1436 'code' => 'alreadyrolled',
1437 'info' => "The page you tried to rollback was already rolled back"
1439 'cantrollback' => array(
1440 'code' => 'onlyauthor',
1441 'info' => "The page you tried to rollback only has one author"
1443 'readonlytext' => array(
1444 'code' => 'readonly',
1445 'info' => "The wiki is currently in read-only mode"
1447 'sessionfailure' => array(
1448 'code' => 'badtoken',
1449 'info' => "Invalid token" ),
1450 'cannotdelete' => array(
1451 'code' => 'cantdelete',
1452 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1454 'notanarticle' => array(
1455 'code' => 'missingtitle',
1456 'info' => "The page you requested doesn't exist"
1458 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1460 'immobile_namespace' => array(
1461 'code' => 'immobilenamespace',
1462 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1464 'articleexists' => array(
1465 'code' => 'articleexists',
1466 'info' => "The destination article already exists and is not a redirect to the source article"
1468 'protectedpage' => array(
1469 'code' => 'protectedpage',
1470 'info' => "You don't have permission to perform this move"
1472 'hookaborted' => array(
1473 'code' => 'hookaborted',
1474 'info' => "The modification you tried to make was aborted by an extension hook"
1476 'cantmove-titleprotected' => array(
1477 'code' => 'protectedtitle',
1478 'info' => "The destination article has been protected from creation"
1480 'imagenocrossnamespace' => array(
1481 'code' => 'nonfilenamespace',
1482 'info' => "Can't move a file to a non-file namespace"
1484 'imagetypemismatch' => array(
1485 'code' => 'filetypemismatch',
1486 'info' => "The new file extension doesn't match its type"
1488 // 'badarticleerror' => shouldn't happen
1489 // 'badtitletext' => shouldn't happen
1490 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1491 'range_block_disabled' => array(
1492 'code' => 'rangedisabled',
1493 'info' => "Blocking IP ranges has been disabled"
1495 'nosuchusershort' => array(
1496 'code' => 'nosuchuser',
1497 'info' => "The user you specified doesn't exist"
1499 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1500 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1501 'ipb_already_blocked' => array(
1502 'code' => 'alreadyblocked',
1503 'info' => "The user you tried to block was already blocked"
1505 'ipb_blocked_as_range' => array(
1506 'code' => 'blockedasrange',
1507 '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."
1509 'ipb_cant_unblock' => array(
1510 'code' => 'cantunblock',
1511 'info' => "The block you specified was not found. It may have been unblocked already"
1513 'mailnologin' => array(
1514 'code' => 'cantsend',
1515 '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"
1517 'ipbblocked' => array(
1518 'code' => 'ipbblocked',
1519 'info' => 'You cannot block or unblock users while you are yourself blocked'
1521 'ipbnounblockself' => array(
1522 'code' => 'ipbnounblockself',
1523 'info' => 'You are not allowed to unblock yourself'
1525 'usermaildisabled' => array(
1526 'code' => 'usermaildisabled',
1527 'info' => "User email has been disabled"
1529 'blockedemailuser' => array(
1530 'code' => 'blockedfrommail',
1531 'info' => "You have been blocked from sending email"
1533 'notarget' => array(
1534 'code' => 'notarget',
1535 'info' => "You have not specified a valid target for this action"
1538 'code' => 'noemail',
1539 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1541 'rcpatroldisabled' => array(
1542 'code' => 'patroldisabled',
1543 'info' => "Patrolling is disabled on this wiki"
1545 'markedaspatrollederror-noautopatrol' => array(
1546 'code' => 'noautopatrol',
1547 'info' => "You don't have permission to patrol your own changes"
1549 'delete-toobig' => array(
1550 'code' => 'bigdelete',
1551 'info' => "You can't delete this page because it has more than \$1 revisions"
1553 'movenotallowedfile' => array(
1554 'code' => 'cantmovefile',
1555 'info' => "You don't have permission to move files"
1557 'userrights-no-interwiki' => array(
1558 'code' => 'nointerwikiuserrights',
1559 'info' => "You don't have permission to change user rights on other wikis"
1561 'userrights-nodatabase' => array(
1562 'code' => 'nosuchdatabase',
1563 'info' => "Database \"\$1\" does not exist or is not local"
1565 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1566 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1567 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1568 'import-rootpage-invalid' => array(
1569 'code' => 'import-rootpage-invalid',
1570 'info' => 'Root page is an invalid title'
1572 'import-rootpage-nosubpage' => array(
1573 'code' => 'import-rootpage-nosubpage',
1574 'info' => 'Namespace "$1" of the root page does not allow subpages'
1577 // API-specific messages
1578 'readrequired' => array(
1579 'code' => 'readapidenied',
1580 'info' => "You need read permission to use this module"
1582 'writedisabled' => array(
1583 'code' => 'noapiwrite',
1584 '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"
1586 'writerequired' => array(
1587 'code' => 'writeapidenied',
1588 'info' => "You're not allowed to edit this wiki through the API"
1590 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1591 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1592 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1593 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1594 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1595 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1596 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1597 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1598 'create-titleexists' => array(
1599 'code' => 'create-titleexists',
1600 'info' => "Existing titles can't be protected with 'create'"
1602 'missingtitle-createonly' => array(
1603 'code' => 'missingtitle-createonly',
1604 'info' => "Missing titles can only be protected with 'create'"
1606 'cantblock' => array( 'code' => 'cantblock',
1607 'info' => "You don't have permission to block users"
1609 'canthide' => array(
1610 'code' => 'canthide',
1611 'info' => "You don't have permission to hide user names from the block log"
1613 'cantblock-email' => array(
1614 'code' => 'cantblock-email',
1615 'info' => "You don't have permission to block users from sending email through the wiki"
1617 'unblock-notarget' => array(
1618 'code' => 'notarget',
1619 'info' => "Either the id or the user parameter must be set"
1621 'unblock-idanduser' => array(
1622 'code' => 'idanduser',
1623 'info' => "The id and user parameters can't be used together"
1625 'cantunblock' => array(
1626 'code' => 'permissiondenied',
1627 'info' => "You don't have permission to unblock users"
1629 'cannotundelete' => array(
1630 'code' => 'cantundelete',
1631 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1633 'permdenied-undelete' => array(
1634 'code' => 'permissiondenied',
1635 'info' => "You don't have permission to restore deleted revisions"
1637 'createonly-exists' => array(
1638 'code' => 'articleexists',
1639 'info' => "The article you tried to create has been created already"
1641 'nocreate-missing' => array(
1642 'code' => 'missingtitle',
1643 'info' => "The article you tried to edit doesn't exist"
1645 'cantchangecontentmodel' => array(
1646 'code' => 'cantchangecontentmodel',
1647 'info' => "You don't have permission to change the content model of a page"
1649 'nosuchrcid' => array(
1650 'code' => 'nosuchrcid',
1651 'info' => "There is no change with rcid \"\$1\""
1653 'protect-invalidaction' => array(
1654 'code' => 'protect-invalidaction',
1655 'info' => "Invalid protection type \"\$1\""
1657 'protect-invalidlevel' => array(
1658 'code' => 'protect-invalidlevel',
1659 'info' => "Invalid protection level \"\$1\""
1661 'toofewexpiries' => array(
1662 'code' => 'toofewexpiries',
1663 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1665 'cantimport' => array(
1666 'code' => 'cantimport',
1667 'info' => "You don't have permission to import pages"
1669 'cantimport-upload' => array(
1670 'code' => 'cantimport-upload',
1671 'info' => "You don't have permission to import uploaded pages"
1673 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1674 'importuploaderrorsize' => array(
1675 'code' => 'filetoobig',
1676 'info' => 'The file you uploaded is bigger than the maximum upload size'
1678 'importuploaderrorpartial' => array(
1679 'code' => 'partialupload',
1680 'info' => 'The file was only partially uploaded'
1682 'importuploaderrortemp' => array(
1683 'code' => 'notempdir',
1684 'info' => 'The temporary upload directory is missing'
1686 'importcantopen' => array(
1687 'code' => 'cantopenfile',
1688 'info' => "Couldn't open the uploaded file"
1690 'import-noarticle' => array(
1691 'code' => 'badinterwiki',
1692 'info' => 'Invalid interwiki title specified'
1694 'importbadinterwiki' => array(
1695 'code' => 'badinterwiki',
1696 'info' => 'Invalid interwiki title specified'
1698 'import-unknownerror' => array(
1699 'code' => 'import-unknownerror',
1700 'info' => "Unknown error on import: \"\$1\""
1702 'cantoverwrite-sharedfile' => array(
1703 'code' => 'cantoverwrite-sharedfile',
1704 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1706 'sharedfile-exists' => array(
1707 'code' => 'fileexists-sharedrepo-perm',
1708 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1710 'mustbeposted' => array(
1711 'code' => 'mustbeposted',
1712 'info' => "The \$1 module requires a POST request"
1716 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1718 'specialpage-cantexecute' => array(
1719 'code' => 'specialpage-cantexecute',
1720 'info' => "You don't have permission to view the results of this special page"
1722 'invalidoldimage' => array(
1723 'code' => 'invalidoldimage',
1724 'info' => 'The oldimage parameter has invalid format'
1726 'nodeleteablefile' => array(
1727 'code' => 'nodeleteablefile',
1728 'info' => 'No such old version of the file'
1730 'fileexists-forbidden' => array(
1731 'code' => 'fileexists-forbidden',
1732 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1734 'fileexists-shared-forbidden' => array(
1735 'code' => 'fileexists-shared-forbidden',
1736 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1738 'filerevert-badversion' => array(
1739 'code' => 'filerevert-badversion',
1740 'info' => 'There is no previous local version of this file with the provided timestamp.'
1743 // ApiEditPage messages
1744 'noimageredirect-anon' => array(
1745 'code' => 'noimageredirect-anon',
1746 'info' => "Anonymous users can't create image redirects"
1748 'noimageredirect-logged' => array(
1749 'code' => 'noimageredirect',
1750 'info' => "You don't have permission to create image redirects"
1752 'spamdetected' => array(
1753 'code' => 'spamdetected',
1754 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1756 'contenttoobig' => array(
1757 'code' => 'contenttoobig',
1758 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1760 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1761 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1762 'wasdeleted' => array(
1763 'code' => 'pagedeleted',
1764 'info' => "The page has been deleted since you fetched its timestamp"
1766 'blankpage' => array(
1767 'code' => 'emptypage',
1768 'info' => "Creating new, empty pages is not allowed"
1770 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1771 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1772 'missingtext' => array(
1774 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1776 'emptynewsection' => array(
1777 'code' => 'emptynewsection',
1778 'info' => 'Creating empty new sections is not possible.'
1780 'revwrongpage' => array(
1781 'code' => 'revwrongpage',
1782 'info' => "r\$1 is not a revision of \"\$2\""
1784 'undo-failure' => array(
1785 'code' => 'undofailure',
1786 'info' => 'Undo failed due to conflicting intermediate edits'
1788 'content-not-allowed-here' => array(
1789 'code' => 'contentnotallowedhere',
1790 'info' => 'Content model "$1" is not allowed at title "$2"'
1793 // Messages from WikiPage::doEit()
1794 'edit-hook-aborted' => array(
1795 'code' => 'edit-hook-aborted',
1796 'info' => "Your edit was aborted by an ArticleSave hook"
1798 'edit-gone-missing' => array(
1799 'code' => 'edit-gone-missing',
1800 'info' => "The page you tried to edit doesn't seem to exist anymore"
1802 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1803 'edit-already-exists' => array(
1804 'code' => 'edit-already-exists',
1805 'info' => 'It seems the page you tried to create already exist'
1809 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1810 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1811 'uploaddisabled' => array(
1812 'code' => 'uploaddisabled',
1813 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1815 'copyuploaddisabled' => array(
1816 'code' => 'copyuploaddisabled',
1817 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1819 'copyuploadbaddomain' => array(
1820 'code' => 'copyuploadbaddomain',
1821 'info' => 'Uploads by URL are not allowed from this domain.'
1823 'copyuploadbadurl' => array(
1824 'code' => 'copyuploadbadurl',
1825 'info' => 'Upload not allowed from this URL.'
1828 'filename-tooshort' => array(
1829 'code' => 'filename-tooshort',
1830 'info' => 'The filename is too short'
1832 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1833 'illegal-filename' => array(
1834 'code' => 'illegal-filename',
1835 'info' => 'The filename is not allowed'
1837 'filetype-missing' => array(
1838 'code' => 'filetype-missing',
1839 'info' => 'The file is missing an extension'
1842 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1844 // @codingStandardsIgnoreEnd
1847 * Helper function for readonly errors
1849 public function dieReadOnly() {
1850 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1851 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1852 array( 'readonlyreason' => wfReadOnlyReason() ) );
1856 * Output the error message related to a certain array
1857 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1859 public function dieUsageMsg( $error ) {
1860 # most of the time we send a 1 element, so we might as well send it as
1861 # a string and make this an array here.
1862 if ( is_string( $error ) ) {
1863 $error = array( $error );
1865 $parsed = $this->parseMsg( $error );
1866 $this->dieUsage( $parsed['info'], $parsed['code'] );
1870 * Will only set a warning instead of failing if the global $wgDebugAPI
1871 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1872 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1875 public function dieUsageMsgOrDebug( $error ) {
1876 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1877 $this->dieUsageMsg( $error );
1880 if ( is_string( $error ) ) {
1881 $error = array( $error );
1883 $parsed = $this->parseMsg( $error );
1884 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1888 * Die with the $prefix.'badcontinue' error. This call is common enough to
1889 * make it into the base method.
1890 * @param bool $condition Will only die if this value is true
1893 protected function dieContinueUsageIf( $condition ) {
1896 'Invalid continue param. You should pass the original value returned by the previous query',
1902 * Return the error message related to a certain array
1903 * @param array $error Element of a getUserPermissionsErrors()-style array
1904 * @return array('code' => code, 'info' => info)
1906 public function parseMsg( $error ) {
1907 $error = (array)$error; // It seems strings sometimes make their way in here
1908 $key = array_shift( $error );
1910 // Check whether the error array was nested
1911 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1912 if ( is_array( $key ) ) {
1914 $key = array_shift( $error );
1917 if ( isset( self
::$messageMap[$key] ) ) {
1919 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1920 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1924 // If the key isn't present, throw an "unknown error"
1925 return $this->parseMsg( array( 'unknownerror', $key ) );
1929 * Internal code errors should be reported with this method
1930 * @param string $method Method or function name
1931 * @param string $message Error message
1932 * @throws MWException
1934 protected static function dieDebug( $method, $message ) {
1935 throw new MWException( "Internal error in $method: $message" );
1940 /************************************************************************//**
1941 * @name Help message generation
1946 * Return the description message.
1948 * @return string|array|Message
1950 protected function getDescriptionMessage() {
1951 return "apihelp-{$this->getModulePath()}-description";
1955 * Get final module description, after hooks have had a chance to tweak it as
1958 * @since 1.25, returns Message[] rather than string[]
1961 public function getFinalDescription() {
1962 $desc = $this->getDescription();
1963 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
1964 $desc = self
::escapeWikiText( $desc );
1965 if ( is_array( $desc ) ) {
1966 $desc = join( "\n", $desc );
1968 $desc = (string)$desc;
1971 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1972 $this->getModulePrefix(),
1973 $this->getModuleName(),
1974 $this->getModulePath(),
1976 if ( !$msg->exists() ) {
1977 $msg = $this->msg( 'api-help-fallback-description', $desc );
1979 $msgs = array( $msg );
1981 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1987 * Get final list of parameters, after hooks have had a chance to
1988 * tweak it as needed.
1990 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1991 * @return array|bool False on no parameters
1992 * @since 1.21 $flags param added
1994 public function getFinalParams( $flags = 0 ) {
1995 $params = $this->getAllowedParams( $flags );
2000 if ( $this->needsToken() ) {
2001 $params['token'] = array(
2002 ApiBase
::PARAM_TYPE
=> 'string',
2003 ApiBase
::PARAM_REQUIRED
=> true,
2004 ApiBase
::PARAM_HELP_MSG
=> array(
2005 'api-help-param-token',
2006 $this->needsToken(),
2008 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2011 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2017 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2020 * @since 1.25, returns array of Message[] rather than array of string[]
2021 * @return array Keys are parameter names, values are arrays of Message objects
2023 public function getFinalParamDescription() {
2024 $prefix = $this->getModulePrefix();
2025 $name = $this->getModuleName();
2026 $path = $this->getModulePath();
2028 $desc = $this->getParamDescription();
2029 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2034 $desc = self
::escapeWikiText( $desc );
2036 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2038 foreach ( $params as $param => $settings ) {
2039 if ( !is_array( $settings ) ) {
2040 $settings = array();
2043 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2044 if ( is_array( $d ) ) {
2045 // Special handling for prop parameters
2046 $d = array_map( function ( $line ) {
2047 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2048 $line = "\n;{$m[1]}:{$m[2]}";
2052 $d = join( ' ', $d );
2055 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2056 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2058 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2059 if ( !$msg->exists() ) {
2060 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2063 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2064 array( $prefix, $param, $name, $path ) );
2066 $this->dieDebug( __METHOD__
,
2067 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2069 $msgs[$param] = array( $msg );
2071 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2072 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2073 $this->dieDebug( __METHOD__
,
2074 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2076 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2077 $this->dieDebug( __METHOD__
,
2078 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2079 'ApiBase::PARAM_TYPE is an array' );
2082 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2083 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2084 if ( isset( $valueMsgs[$value] ) ) {
2085 $msg = $valueMsgs[$value];
2087 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2089 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2090 array( $prefix, $param, $name, $path, $value ) );
2092 $m = new ApiHelpParamValueMessage(
2094 array( $m->getKey(), 'api-help-param-no-description' ),
2097 $msgs[$param][] = $m->setContext( $this->getContext() );
2099 $this->dieDebug( __METHOD__
,
2100 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2105 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2106 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2107 $this->dieDebug( __METHOD__
,
2108 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2110 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2111 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2112 array( $prefix, $param, $name, $path ) );
2114 $msgs[$param][] = $m;
2116 $this->dieDebug( __METHOD__
,
2117 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2123 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2129 * Generates the list of flags for the help screen and for action=paraminfo
2131 * Corresponding messages: api-help-flag-deprecated,
2132 * api-help-flag-internal, api-help-flag-readrights,
2133 * api-help-flag-writerights, api-help-flag-mustbeposted
2137 protected function getHelpFlags() {
2140 if ( $this->isDeprecated() ) {
2141 $flags[] = 'deprecated';
2143 if ( $this->isInternal() ) {
2144 $flags[] = 'internal';
2146 if ( $this->isReadMode() ) {
2147 $flags[] = 'readrights';
2149 if ( $this->isWriteMode() ) {
2150 $flags[] = 'writerights';
2152 if ( $this->mustBePosted() ) {
2153 $flags[] = 'mustbeposted';
2160 * Called from ApiHelp before the pieces are joined together and returned.
2162 * This exists mainly for ApiMain to add the Permissions and Credits
2163 * sections. Other modules probably don't need it.
2165 * @param string[] &$help Array of help data
2166 * @param array $options Options passed to ApiHelp::getHelp
2168 public function modifyHelp( array &$help, array $options ) {
2173 /************************************************************************//**
2179 * Profiling: total module execution time
2181 private $mTimeIn = 0, $mModuleTime = 0;
2184 * Get the name of the module as shown in the profiler log
2186 * @param DatabaseBase|bool $db
2190 public function getModuleProfileName( $db = false ) {
2192 return 'API:' . $this->mModuleName
. '-DB';
2195 return 'API:' . $this->mModuleName
;
2199 * Start module profiling
2201 public function profileIn() {
2202 if ( $this->mTimeIn
!== 0 ) {
2203 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2205 $this->mTimeIn
= microtime( true );
2206 wfProfileIn( $this->getModuleProfileName() );
2210 * End module profiling
2212 public function profileOut() {
2213 if ( $this->mTimeIn
=== 0 ) {
2214 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2216 if ( $this->mDBTimeIn
!== 0 ) {
2219 'Must be called after database profiling is done with profileDBOut()'
2223 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2225 wfProfileOut( $this->getModuleProfileName() );
2229 * When modules crash, sometimes it is needed to do a profileOut() regardless
2230 * of the profiling state the module was in. This method does such cleanup.
2232 public function safeProfileOut() {
2233 if ( $this->mTimeIn
!== 0 ) {
2234 if ( $this->mDBTimeIn
!== 0 ) {
2235 $this->profileDBOut();
2237 $this->profileOut();
2242 * Total time the module was executed
2245 public function getProfileTime() {
2246 if ( $this->mTimeIn
!== 0 ) {
2247 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2250 return $this->mModuleTime
;
2254 * Profiling: database execution time
2256 private $mDBTimeIn = 0, $mDBTime = 0;
2259 * Start module profiling
2261 public function profileDBIn() {
2262 if ( $this->mTimeIn
=== 0 ) {
2265 'Must be called while profiling the entire module with profileIn()'
2268 if ( $this->mDBTimeIn
!== 0 ) {
2269 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2271 $this->mDBTimeIn
= microtime( true );
2272 wfProfileIn( $this->getModuleProfileName( true ) );
2276 * End database profiling
2278 public function profileDBOut() {
2279 if ( $this->mTimeIn
=== 0 ) {
2280 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2281 'the entire module with profileIn()' );
2283 if ( $this->mDBTimeIn
=== 0 ) {
2284 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2287 $time = microtime( true ) - $this->mDBTimeIn
;
2288 $this->mDBTimeIn
= 0;
2290 $this->mDBTime +
= $time;
2291 $this->getMain()->mDBTime +
= $time;
2292 wfProfileOut( $this->getModuleProfileName( true ) );
2296 * Total time the module used the database
2299 public function getProfileDBTime() {
2300 if ( $this->mDBTimeIn
!== 0 ) {
2301 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2304 return $this->mDBTime
;
2308 * Write logging information for API features to a debug log, for usage
2310 * @param string $feature Feature being used.
2312 protected function logFeatureUsage( $feature ) {
2313 $request = $this->getRequest();
2314 $s = '"' . addslashes( $feature ) . '"' .
2315 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2316 ' "' . $request->getIP() . '"' .
2317 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2318 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2319 wfDebugLog( 'api-feature-usage', $s, 'private' );
2324 /************************************************************************//**
2329 /// @deprecated since 1.24
2330 const PROP_ROOT
= 'ROOT';
2331 /// @deprecated since 1.24
2332 const PROP_LIST
= 'LIST';
2333 /// @deprecated since 1.24
2334 const PROP_TYPE
= 0;
2335 /// @deprecated since 1.24
2336 const PROP_NULLABLE
= 1;
2339 * Formerly returned a string that identifies the version of the extending
2340 * class. Typically included the class name, the svn revision, timestamp,
2341 * and last author. Usually done with SVN's Id keyword
2343 * @deprecated since 1.21, version string is no longer supported
2346 public function getVersion() {
2347 wfDeprecated( __METHOD__
, '1.21' );
2352 * Formerly used to fetch a list of possible properites in the result,
2353 * somehow organized with respect to the prop parameter that causes them to
2354 * be returned. The specific semantics of the return value was never
2355 * specified. Since this was never possible to be accurately updated, it
2358 * @deprecated since 1.24
2359 * @return array|bool
2361 protected function getResultProperties() {
2362 wfDeprecated( __METHOD__
, '1.24' );
2367 * @see self::getResultProperties()
2368 * @deprecated since 1.24
2369 * @return array|bool
2371 public function getFinalResultProperties() {
2372 wfDeprecated( __METHOD__
, '1.24' );
2377 * @see self::getResultProperties()
2378 * @deprecated since 1.24
2380 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2381 wfDeprecated( __METHOD__
, '1.24' );
2385 * @see self::getPossibleErrors()
2386 * @deprecated since 1.24
2389 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2390 wfDeprecated( __METHOD__
, '1.24' );
2395 * @see self::getPossibleErrors()
2396 * @deprecated since 1.24
2399 public function getRequireMaxOneParameterErrorMessages( $params ) {
2400 wfDeprecated( __METHOD__
, '1.24' );
2405 * @see self::getPossibleErrors()
2406 * @deprecated since 1.24
2409 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2410 wfDeprecated( __METHOD__
, '1.24' );
2415 * @see self::getPossibleErrors()
2416 * @deprecated since 1.24
2419 public function getTitleOrPageIdErrorMessage() {
2420 wfDeprecated( __METHOD__
, '1.24' );
2425 * This formerly attempted to return a list of all possible errors returned
2426 * by the module. However, this was impossible to maintain in many cases
2427 * since errors could come from other areas of MediaWiki and in some cases
2428 * from arbitrary extension hooks. Since a partial list claiming to be
2429 * comprehensive is unlikely to be useful, it was removed.
2431 * @deprecated since 1.24
2434 public function getPossibleErrors() {
2435 wfDeprecated( __METHOD__
, '1.24' );
2440 * @see self::getPossibleErrors()
2441 * @deprecated since 1.24
2444 public function getFinalPossibleErrors() {
2445 wfDeprecated( __METHOD__
, '1.24' );
2450 * @see self::getPossibleErrors()
2451 * @deprecated since 1.24
2454 public function parseErrors( $errors ) {
2455 wfDeprecated( __METHOD__
, '1.24' );
2460 * Returns the description string for this module
2462 * Ignored if an i18n message exists for
2463 * "apihelp-{$this->getModulePathString()}-description".
2465 * @deprecated since 1.25
2466 * @return Message|string|array
2468 protected function getDescription() {
2473 * Returns an array of parameter descriptions.
2475 * For each parameter, ignored if an i18n message exists for the parameter.
2476 * By default that message is
2477 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2478 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2479 * self::getFinalParams().
2481 * @deprecated since 1.25
2482 * @return array|bool False on no parameter descriptions
2484 protected function getParamDescription() {
2489 * Returns usage examples for this module.
2491 * Return value as an array is either:
2492 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2494 * - sequential numeric keys with even-numbered keys being display-text
2495 * and odd-numbered keys being partial urls
2496 * - partial URLs as keys with display-text (string or array-to-be-joined)
2498 * Return value as a string is the same as an array with a numeric key and
2499 * that value, and boolean false means "no examples".
2501 * @deprecated since 1.25, use getExamplesMessages() instead
2502 * @return bool|string|array
2504 protected function getExamples() {
2509 * Generates help message for this module, or false if there is no description
2510 * @deprecated since 1.25
2511 * @return string|bool
2513 public function makeHelpMsg() {
2514 wfDeprecated( __METHOD__
, '1.25' );
2515 static $lnPrfx = "\n ";
2517 $msg = $this->getFinalDescription();
2519 if ( $msg !== false ) {
2521 if ( !is_array( $msg ) ) {
2526 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2528 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2530 if ( $this->isReadMode() ) {
2531 $msg .= "\nThis module requires read rights";
2533 if ( $this->isWriteMode() ) {
2534 $msg .= "\nThis module requires write rights";
2536 if ( $this->mustBePosted() ) {
2537 $msg .= "\nThis module only accepts POST requests";
2539 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2540 $this->mustBePosted()
2546 $paramsMsg = $this->makeHelpMsgParameters();
2547 if ( $paramsMsg !== false ) {
2548 $msg .= "Parameters:\n$paramsMsg";
2551 $examples = $this->getExamples();
2553 if ( !is_array( $examples ) ) {
2558 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2559 foreach ( $examples as $k => $v ) {
2560 if ( is_numeric( $k ) ) {
2563 if ( is_array( $v ) ) {
2564 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2566 $msgExample = " $v";
2569 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2579 * @deprecated since 1.25
2580 * @param string $item
2583 private function indentExampleText( $item ) {
2588 * @deprecated since 1.25
2589 * @param string $prefix Text to split output items
2590 * @param string $title What is being output
2591 * @param string|array $input
2594 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2595 wfDeprecated( __METHOD__
, '1.25' );
2596 if ( $input === false ) {
2599 if ( !is_array( $input ) ) {
2600 $input = array( $input );
2603 if ( count( $input ) > 0 ) {
2605 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2609 $msg .= implode( $prefix, $input ) . "\n";
2618 * Generates the parameter descriptions for this module, to be displayed in the
2620 * @deprecated since 1.25
2621 * @return string|bool
2623 public function makeHelpMsgParameters() {
2624 wfDeprecated( __METHOD__
, '1.25' );
2625 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2628 $paramsDescription = $this->getFinalParamDescription();
2630 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2631 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2632 foreach ( $params as $paramName => $paramSettings ) {
2633 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2634 if ( is_array( $desc ) ) {
2635 $desc = implode( $paramPrefix, $desc );
2639 if ( !is_array( $paramSettings ) ) {
2640 $paramSettings = array(
2641 self
::PARAM_DFLT
=> $paramSettings,
2645 //handle missing type
2646 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2647 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2648 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2650 if ( is_bool( $dflt ) ) {
2651 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2652 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2653 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2654 } elseif ( is_int( $dflt ) ) {
2655 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2659 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2660 && $paramSettings[self
::PARAM_DEPRECATED
]
2662 $desc = "DEPRECATED! $desc";
2665 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2666 && $paramSettings[self
::PARAM_REQUIRED
]
2668 $desc .= $paramPrefix . "This parameter is required";
2671 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2672 ?
$paramSettings[self
::PARAM_TYPE
]
2674 if ( isset( $type ) ) {
2675 $hintPipeSeparated = true;
2676 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2677 ?
$paramSettings[self
::PARAM_ISMULTI
]
2680 $prompt = 'Values (separate with \'|\'): ';
2682 $prompt = 'One value: ';
2685 if ( $type === 'submodule' ) {
2686 $type = $this->getModuleManager()->getNames( $paramName );
2689 if ( is_array( $type ) ) {
2691 $nothingPrompt = '';
2692 foreach ( $type as $t ) {
2694 $nothingPrompt = 'Can be empty, or ';
2699 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2700 $choicesstring = implode( ', ', $choices );
2701 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2702 $hintPipeSeparated = false;
2706 // Special handling because namespaces are
2707 // type-limited, yet they are not given
2708 $desc .= $paramPrefix . $prompt;
2709 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2710 100, $descWordwrap );
2711 $hintPipeSeparated = false;
2714 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2715 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2716 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2718 $desc .= ' allowed';
2721 $s = $multi ?
's' : '';
2722 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2723 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2724 if ( $hasMin ||
$hasMax ) {
2726 $intRangeStr = "The value$s must be no less than " .
2727 "{$paramSettings[self::PARAM_MIN]}";
2728 } elseif ( !$hasMin ) {
2729 $intRangeStr = "The value$s must be no more than " .
2730 "{$paramSettings[self::PARAM_MAX]}";
2732 $intRangeStr = "The value$s must be between " .
2733 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2736 $desc .= $paramPrefix . $intRangeStr;
2740 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2746 if ( $hintPipeSeparated ) {
2747 $desc .= $paramPrefix . "Separate values with '|'";
2750 $isArray = is_array( $type );
2752 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2754 $desc .= $paramPrefix . "Maximum number of values " .
2755 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2760 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2761 if ( !is_null( $default ) && $default !== false ) {
2762 $desc .= $paramPrefix . "Default: $default";
2765 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2778 * For really cool vim folding this needs to be at the end:
2779 * vim: foldmarker=@{,@} foldmethod=marker