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;
101 /** @var array Maps extension paths to info arrays */
102 private static $extensionInfo = null;
105 private $mMainModule;
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
110 /** @var array|null|bool */
111 private $mModuleSource = false;
114 * @param ApiMain $mainModule
115 * @param string $moduleName Name of this module
116 * @param string $modulePrefix Prefix to use for parameter names
118 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
119 $this->mMainModule
= $mainModule;
120 $this->mModuleName
= $moduleName;
121 $this->mModulePrefix
= $modulePrefix;
123 if ( !$this->isMain() ) {
124 $this->setContext( $mainModule->getContext() );
129 /************************************************************************//**
130 * @name Methods to implement
135 * Evaluates the parameters, performs the requested query, and sets up
136 * the result. Concrete implementations of ApiBase must override this
137 * method to provide whatever functionality their module offers.
138 * Implementations must not produce any output on their own and are not
139 * expected to handle any errors.
141 * The execute() method will be invoked directly by ApiMain immediately
142 * before the result of the module is output. Aside from the
143 * constructor, implementations should assume that no other methods
144 * will be called externally on the module before the result is
147 * The result data should be stored in the ApiResult object available
148 * through getResult().
150 abstract public function execute();
153 * Get the module manager, or null if this module has no sub-modules
155 * @return ApiModuleManager
157 public function getModuleManager() {
162 * If the module may only be used with a certain format module,
163 * it should override this method to return an instance of that formatter.
164 * A value of null means the default format will be used.
165 * @note Do not use this just because you don't want to support non-json
166 * formats. This should be used only when there is a fundamental
167 * requirement for a specific format.
168 * @return mixed Instance of a derived class of ApiFormatBase, or null
170 public function getCustomPrinter() {
175 * Returns usage examples for this module.
177 * Return value has query strings as keys, with values being either strings
178 * (message key), arrays (message key + parameter), or Message objects.
180 * Do not call this base class implementation when overriding this method.
185 protected function getExamplesMessages() {
186 // Fall back to old non-localised method
189 $examples = $this->getExamples();
191 if ( !is_array( $examples ) ) {
192 $examples = array( $examples );
193 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
194 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
195 !preg_match( '/^\s*api\.php\?/', $examples[0] )
197 // Fix up the ugly "even numbered elements are description, odd
198 // numbered elemts are the link" format (see doc for self::getExamples)
200 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
201 $tmp[$examples[$i +
1]] = $examples[$i];
206 foreach ( $examples as $k => $v ) {
207 if ( is_numeric( $k ) ) {
212 $msg = self
::escapeWikiText( $v );
213 if ( is_array( $msg ) ) {
214 $msg = join( " ", $msg );
218 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
219 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
227 * Return links to more detailed help pages about the module.
228 * @since 1.25, returning boolean false is deprecated
229 * @return string|array
231 public function getHelpUrls() {
236 * Returns an array of allowed parameters (parameter name) => (default
237 * value) or (parameter name) => (array with PARAM_* constants as keys)
238 * Don't call this function directly: use getFinalParams() to allow
239 * hooks to modify parameters as needed.
241 * Some derived classes may choose to handle an integer $flags parameter
242 * in the overriding methods. Callers of this method can pass zero or
243 * more OR-ed flags like GET_VALUES_FOR_HELP.
247 protected function getAllowedParams( /* $flags = 0 */ ) {
248 // int $flags is not declared because it causes "Strict standards"
249 // warning. Most derived classes do not implement it.
254 * Indicates if this module needs maxlag to be checked
257 public function shouldCheckMaxlag() {
262 * Indicates whether this module requires read rights
265 public function isReadMode() {
270 * Indicates whether this module requires write mode
273 public function isWriteMode() {
278 * Indicates whether this module must be called with a POST request
281 public function mustBePosted() {
282 return $this->needsToken() !== false;
286 * Indicates whether this module is deprecated
290 public function isDeprecated() {
295 * Indicates whether this module is "internal"
296 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
300 public function isInternal() {
305 * Returns the token type this module requires in order to execute.
307 * Modules are strongly encouraged to use the core 'csrf' type unless they
308 * have specialized security needs. If the token type is not one of the
309 * core types, you must use the ApiQueryTokensRegisterTypes hook to
312 * Returning a non-falsey value here will force the addition of an
313 * appropriate 'token' parameter in self::getFinalParams(). Also,
314 * self::mustBePosted() must return true when tokens are used.
316 * In previous versions of MediaWiki, true was a valid return value.
317 * Returning true will generate errors indicating that the API module needs
320 * @return string|false
322 public function needsToken() {
327 * Fetch the salt used in the Web UI corresponding to this module.
329 * Only override this if the Web UI uses a token with a non-constant salt.
332 * @param array $params All supplied parameters for the module
333 * @return string|array|null
335 protected function getWebUITokenSalt( array $params ) {
341 /************************************************************************//**
342 * @name Data access methods
347 * Get the name of the module being executed by this instance
350 public function getModuleName() {
351 return $this->mModuleName
;
355 * Get parameter prefix (usually two letters or an empty string).
358 public function getModulePrefix() {
359 return $this->mModulePrefix
;
363 * Get the main module
366 public function getMain() {
367 return $this->mMainModule
;
371 * Returns true if this module is the main module ($this === $this->mMainModule),
375 public function isMain() {
376 return $this === $this->mMainModule
;
380 * Get the parent of this module
382 * @return ApiBase|null
384 public function getParent() {
385 return $this->isMain() ?
null : $this->getMain();
389 * Returns true if the current request breaks the same-origin policy.
391 * For example, json with callbacks.
393 * https://en.wikipedia.org/wiki/Same-origin_policy
398 public function lacksSameOriginSecurity() {
399 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
403 * Get the path to this module
408 public function getModulePath() {
409 if ( $this->isMain() ) {
411 } elseif ( $this->getParent()->isMain() ) {
412 return $this->getModuleName();
414 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
419 * Get a module from its module path
422 * @param string $path
423 * @return ApiBase|null
424 * @throws UsageException
426 public function getModuleFromPath( $path ) {
427 $module = $this->getMain();
428 if ( $path === 'main' ) {
432 $parts = explode( '+', $path );
433 if ( count( $parts ) === 1 ) {
434 // In case the '+' was typed into URL, it resolves as a space
435 $parts = explode( ' ', $path );
438 $count = count( $parts );
439 for ( $i = 0; $i < $count; $i++
) {
441 $manager = $parent->getModuleManager();
442 if ( $manager === null ) {
443 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
444 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
446 $module = $manager->getModule( $parts[$i] );
448 if ( $module === null ) {
449 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
451 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
461 * Get the result object
464 public function getResult() {
465 // Main module has getResult() method overridden
466 // Safety - avoid infinite loop:
467 if ( $this->isMain() ) {
468 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
471 return $this->getMain()->getResult();
475 * Get the result data array (read-only)
478 public function getResultData() {
479 return $this->getResult()->getData();
483 * Gets a default slave database connection object
484 * @return DatabaseBase
486 protected function getDB() {
487 if ( !isset( $this->mSlaveDB
) ) {
488 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
491 return $this->mSlaveDB
;
496 /************************************************************************//**
497 * @name Parameter handling
502 * This method mangles parameter name based on the prefix supplied to the constructor.
503 * Override this method to change parameter name during runtime
504 * @param string $paramName Parameter name
505 * @return string Prefixed parameter name
507 public function encodeParamName( $paramName ) {
508 return $this->mModulePrefix
. $paramName;
512 * Using getAllowedParams(), this function makes an array of the values
513 * provided by the user, with key being the name of the variable, and
514 * value - validated value from user or default. limits will not be
515 * parsed if $parseLimit is set to false; use this when the max
516 * limit is not definitive yet, e.g. when getting revisions.
517 * @param bool $parseLimit True by default
520 public function extractRequestParams( $parseLimit = true ) {
521 // Cache parameters, for performance and to avoid bug 24564.
522 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
523 $params = $this->getFinalParams();
526 if ( $params ) { // getFinalParams() can return false
527 foreach ( $params as $paramName => $paramSettings ) {
528 $results[$paramName] = $this->getParameterFromSettings(
529 $paramName, $paramSettings, $parseLimit );
532 $this->mParamCache
[$parseLimit] = $results;
535 return $this->mParamCache
[$parseLimit];
539 * Get a value for the given parameter
540 * @param string $paramName Parameter name
541 * @param bool $parseLimit See extractRequestParams()
542 * @return mixed Parameter value
544 protected function getParameter( $paramName, $parseLimit = true ) {
545 $params = $this->getFinalParams();
546 $paramSettings = $params[$paramName];
548 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
552 * Die if none or more than one of a certain set of parameters is set and not false.
554 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
555 * @param string $required,... Names of parameters of which exactly one must be set
557 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
558 $required = func_get_args();
559 array_shift( $required );
560 $p = $this->getModulePrefix();
562 $intersection = array_intersect( array_keys( array_filter( $params,
563 array( $this, "parameterNotEmpty" ) ) ), $required );
565 if ( count( $intersection ) > 1 ) {
567 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
569 } elseif ( count( $intersection ) == 0 ) {
571 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
578 * Die if more than one of a certain set of parameters is set and not false.
580 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
581 * @param string $required,... Names of parameters of which at most one must be set
583 public function requireMaxOneParameter( $params, $required /*...*/ ) {
584 $required = func_get_args();
585 array_shift( $required );
586 $p = $this->getModulePrefix();
588 $intersection = array_intersect( array_keys( array_filter( $params,
589 array( $this, "parameterNotEmpty" ) ) ), $required );
591 if ( count( $intersection ) > 1 ) {
593 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
600 * Die if none of a certain set of parameters is set and not false.
603 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
604 * @param string $required,... Names of parameters of which at least one must be set
606 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
607 $required = func_get_args();
608 array_shift( $required );
609 $p = $this->getModulePrefix();
611 $intersection = array_intersect(
612 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
616 if ( count( $intersection ) == 0 ) {
617 $this->dieUsage( "At least one of the parameters {$p}" .
618 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
623 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
625 * @param object $x Parameter to check is not null/false
628 private function parameterNotEmpty( $x ) {
629 return !is_null( $x ) && $x !== false;
633 * Get a WikiPage object from a title or pageid param, if possible.
634 * Can die, if no param is set or if the title or page id is not valid.
636 * @param array $params
637 * @param bool|string $load Whether load the object's state from the database:
638 * - false: don't load (if the pageid is given, it will still be loaded)
639 * - 'fromdb': load from a slave database
640 * - 'fromdbmaster': load from the master database
643 public function getTitleOrPageId( $params, $load = false ) {
644 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
647 if ( isset( $params['title'] ) ) {
648 $titleObj = Title
::newFromText( $params['title'] );
649 if ( !$titleObj ||
$titleObj->isExternal() ) {
650 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
652 if ( !$titleObj->canExist() ) {
653 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
655 $pageObj = WikiPage
::factory( $titleObj );
656 if ( $load !== false ) {
657 $pageObj->loadPageData( $load );
659 } elseif ( isset( $params['pageid'] ) ) {
660 if ( $load === false ) {
663 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
665 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
673 * Return true if we're to watch the page, false if not, null if no change.
674 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
675 * @param Title $titleObj The page under consideration
676 * @param string $userOption The user option to consider when $watchlist=preferences.
677 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
680 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
682 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
684 switch ( $watchlist ) {
692 # If the user is already watching, don't bother checking
693 if ( $userWatching ) {
696 # If no user option was passed, use watchdefault and watchcreations
697 if ( is_null( $userOption ) ) {
698 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
699 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
702 # Watch the article based on the user preference
703 return $this->getUser()->getBoolOption( $userOption );
706 return $userWatching;
709 return $userWatching;
714 * Using the settings determine the value for the given parameter
716 * @param string $paramName Parameter name
717 * @param array|mixed $paramSettings Default value or an array of settings
718 * using PARAM_* constants.
719 * @param bool $parseLimit Parse limit?
720 * @return mixed Parameter value
722 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
723 // Some classes may decide to change parameter names
724 $encParamName = $this->encodeParamName( $paramName );
726 if ( !is_array( $paramSettings ) ) {
727 $default = $paramSettings;
729 $type = gettype( $paramSettings );
734 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
735 ?
$paramSettings[self
::PARAM_DFLT
]
737 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
738 ?
$paramSettings[self
::PARAM_ISMULTI
]
740 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
741 ?
$paramSettings[self
::PARAM_TYPE
]
743 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
744 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
746 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
747 ?
$paramSettings[self
::PARAM_DEPRECATED
]
749 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
750 ?
$paramSettings[self
::PARAM_REQUIRED
]
753 // When type is not given, and no choices, the type is the same as $default
754 if ( !isset( $type ) ) {
755 if ( isset( $default ) ) {
756 $type = gettype( $default );
758 $type = 'NULL'; // allow everything
763 if ( $type == 'boolean' ) {
764 if ( isset( $default ) && $default !== false ) {
765 // Having a default value of anything other than 'false' is not allowed
768 "Boolean param $encParamName's default is set to '$default'. " .
769 "Boolean parameters must default to false."
773 $value = $this->getMain()->getCheck( $encParamName );
774 } elseif ( $type == 'upload' ) {
775 if ( isset( $default ) ) {
776 // Having a default value is not allowed
779 "File upload param $encParamName's default is set to " .
780 "'$default'. File upload parameters may not have a default." );
783 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
785 $value = $this->getMain()->getUpload( $encParamName );
786 if ( !$value->exists() ) {
787 // This will get the value without trying to normalize it
788 // (because trying to normalize a large binary file
789 // accidentally uploaded as a field fails spectacularly)
790 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
791 if ( $value !== null ) {
793 "File upload param $encParamName is not a file upload; " .
794 "be sure to use multipart/form-data for your POST and include " .
795 "a filename in the Content-Disposition header.",
796 "badupload_{$encParamName}"
801 $value = $this->getMain()->getVal( $encParamName, $default );
803 if ( isset( $value ) && $type == 'namespace' ) {
804 $type = MWNamespace
::getValidNamespaces();
806 if ( isset( $value ) && $type == 'submodule' ) {
807 $type = $this->getModuleManager()->getNames( $paramName );
811 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
812 $value = $this->parseMultiValue(
816 is_array( $type ) ?
$type : null
820 // More validation only when choices were not given
821 // choices were validated in parseMultiValue()
822 if ( isset( $value ) ) {
823 if ( !is_array( $type ) ) {
825 case 'NULL': // nothing to do
828 if ( $required && $value === '' ) {
829 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
832 case 'integer': // Force everything using intval() and optionally validate limits
833 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
834 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
835 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
836 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
838 if ( is_array( $value ) ) {
839 $value = array_map( 'intval', $value );
840 if ( !is_null( $min ) ||
!is_null( $max ) ) {
841 foreach ( $value as &$v ) {
842 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
846 $value = intval( $value );
847 if ( !is_null( $min ) ||
!is_null( $max ) ) {
848 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
853 if ( !$parseLimit ) {
854 // Don't do any validation whatsoever
857 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
858 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
862 "MAX1 or MAX2 are not defined for the limit $encParamName"
866 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
868 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
869 if ( $value == 'max' ) {
870 $value = $this->getMain()->canApiHighLimits()
871 ?
$paramSettings[self
::PARAM_MAX2
]
872 : $paramSettings[self
::PARAM_MAX
];
873 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
875 $value = intval( $value );
876 $this->validateLimit(
880 $paramSettings[self
::PARAM_MAX
],
881 $paramSettings[self
::PARAM_MAX2
]
887 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
891 if ( is_array( $value ) ) {
892 foreach ( $value as $key => $val ) {
893 $value[$key] = $this->validateTimestamp( $val, $encParamName );
896 $value = $this->validateTimestamp( $value, $encParamName );
900 if ( is_array( $value ) ) {
901 foreach ( $value as $key => $val ) {
902 $value[$key] = $this->validateUser( $val, $encParamName );
905 $value = $this->validateUser( $value, $encParamName );
908 case 'upload': // nothing to do
911 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
915 // Throw out duplicates if requested
916 if ( !$dupes && is_array( $value ) ) {
917 $value = array_unique( $value );
920 // Set a warning if a deprecated parameter has been passed
921 if ( $deprecated && $value !== false ) {
922 $this->setWarning( "The $encParamName parameter has been deprecated." );
924 } elseif ( $required ) {
925 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
932 * Return an array of values that were given in a 'a|b|c' notation,
933 * after it optionally validates them against the list allowed values.
935 * @param string $valueName The name of the parameter (for error
937 * @param mixed $value The value being parsed
938 * @param bool $allowMultiple Can $value contain more than one value
940 * @param string[]|null $allowedValues An array of values to check against. If
941 * null, all values are accepted.
942 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
944 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
945 if ( trim( $value ) === '' && $allowMultiple ) {
949 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
950 // because it unstubs $wgUser
951 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
952 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
956 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
957 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
958 "the limit is $sizeLimit" );
961 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
962 // Bug 33482 - Allow entries with | in them for non-multiple values
963 if ( in_array( $value, $allowedValues, true ) ) {
967 $possibleValues = is_array( $allowedValues )
968 ?
"of '" . implode( "', '", $allowedValues ) . "'"
971 "Only one $possibleValues is allowed for parameter '$valueName'",
972 "multival_$valueName"
976 if ( is_array( $allowedValues ) ) {
977 // Check for unknown values
978 $unknown = array_diff( $valuesList, $allowedValues );
979 if ( count( $unknown ) ) {
980 if ( $allowMultiple ) {
981 $s = count( $unknown ) > 1 ?
's' : '';
982 $vals = implode( ", ", $unknown );
983 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
986 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
991 // Now throw them out
992 $valuesList = array_intersect( $valuesList, $allowedValues );
995 return $allowMultiple ?
$valuesList : $valuesList[0];
999 * Validate the value against the minimum and user/bot maximum limits.
1000 * Prints usage info on failure.
1001 * @param string $paramName Parameter name
1002 * @param int $value Parameter value
1003 * @param int|null $min Minimum value
1004 * @param int|null $max Maximum value for users
1005 * @param int $botMax Maximum value for sysops/bots
1006 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1008 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1009 if ( !is_null( $min ) && $value < $min ) {
1011 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1012 $this->warnOrDie( $msg, $enforceLimits );
1016 // Minimum is always validated, whereas maximum is checked only if not
1017 // running in internal call mode
1018 if ( $this->getMain()->isInternalMode() ) {
1022 // Optimization: do not check user's bot status unless really needed -- skips db query
1023 // assumes $botMax >= $max
1024 if ( !is_null( $max ) && $value > $max ) {
1025 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1026 if ( $value > $botMax ) {
1027 $msg = $this->encodeParamName( $paramName ) .
1028 " may not be over $botMax (set to $value) for bots or sysops";
1029 $this->warnOrDie( $msg, $enforceLimits );
1033 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1034 $this->warnOrDie( $msg, $enforceLimits );
1041 * Validate and normalize of parameters of type 'timestamp'
1042 * @param string $value Parameter value
1043 * @param string $encParamName Parameter name
1044 * @return string Validated and normalized parameter
1046 protected function validateTimestamp( $value, $encParamName ) {
1047 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1048 if ( $unixTimestamp === false ) {
1050 "Invalid value '$value' for timestamp parameter $encParamName",
1051 "badtimestamp_{$encParamName}"
1055 return wfTimestamp( TS_MW
, $unixTimestamp );
1059 * Validate the supplied token.
1062 * @param string $token Supplied token
1063 * @param array $params All supplied parameters for the module
1065 * @throws MWException
1067 final public function validateToken( $token, array $params ) {
1068 $tokenType = $this->needsToken();
1069 $salts = ApiQueryTokens
::getTokenTypeSalts();
1070 if ( !isset( $salts[$tokenType] ) ) {
1071 throw new MWException(
1072 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1073 'without registering it'
1077 if ( $this->getUser()->matchEditToken(
1085 $webUiSalt = $this->getWebUITokenSalt( $params );
1086 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1098 * Validate and normalize of parameters of type 'user'
1099 * @param string $value Parameter value
1100 * @param string $encParamName Parameter name
1101 * @return string Validated and normalized parameter
1103 private function validateUser( $value, $encParamName ) {
1104 $title = Title
::makeTitleSafe( NS_USER
, $value );
1105 if ( $title === null ) {
1107 "Invalid value '$value' for user parameter $encParamName",
1108 "baduser_{$encParamName}"
1112 return $title->getText();
1117 /************************************************************************//**
1118 * @name Utility methods
1123 * Set a watch (or unwatch) based the based on a watchlist parameter.
1124 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1125 * @param Title $titleObj The article's title to change
1126 * @param string $userOption The user option to consider when $watch=preferences
1128 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1129 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1130 if ( $value === null ) {
1134 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1138 * Truncate an array to a certain length.
1139 * @param array $arr Array to truncate
1140 * @param int $limit Maximum length
1141 * @return bool True if the array was truncated, false otherwise
1143 public static function truncateArray( &$arr, $limit ) {
1145 while ( count( $arr ) > $limit ) {
1154 * Gets the user for whom to get the watchlist
1156 * @param array $params
1159 public function getWatchlistUser( $params ) {
1160 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1161 $user = User
::newFromName( $params['owner'], false );
1162 if ( !( $user && $user->getId() ) ) {
1163 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1165 $token = $user->getOption( 'watchlisttoken' );
1166 if ( $token == '' ||
$token != $params['token'] ) {
1168 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1173 if ( !$this->getUser()->isLoggedIn() ) {
1174 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1176 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1177 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1179 $user = $this->getUser();
1186 * A subset of wfEscapeWikiText for BC texts
1189 * @param string|array $v
1190 * @return string|array
1192 private static function escapeWikiText( $v ) {
1193 if ( is_array( $v ) ) {
1194 return array_map( 'self::escapeWikiText', $v );
1196 return strtr( $v, array(
1197 '__' => '__', '{' => '{', '}' => '}',
1198 '[[Category:' => '[[:Category:',
1199 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1205 * Create a Message from a string or array
1207 * A string is used as a message key. An array has the message key as the
1208 * first value and message parameters as subsequent values.
1211 * @param string|array|Message $msg
1212 * @param IContextSource $context
1213 * @param array $params
1214 * @return Message|null
1216 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1217 if ( is_string( $msg ) ) {
1218 $msg = wfMessage( $msg );
1219 } elseif ( is_array( $msg ) ) {
1220 $msg = call_user_func_array( 'wfMessage', $msg );
1222 if ( !$msg instanceof Message
) {
1226 $msg->setContext( $context );
1228 $msg->params( $params );
1236 /************************************************************************//**
1237 * @name Warning and error reporting
1242 * Set warning section for this module. Users should monitor this
1243 * section to notice any changes in API. Multiple calls to this
1244 * function will result in the warning messages being separated by
1246 * @param string $warning Warning message
1248 public function setWarning( $warning ) {
1249 $result = $this->getResult();
1250 $data = $result->getData();
1251 $moduleName = $this->getModuleName();
1252 if ( isset( $data['warnings'][$moduleName] ) ) {
1253 // Don't add duplicate warnings
1254 $oldWarning = $data['warnings'][$moduleName]['*'];
1255 $warnPos = strpos( $oldWarning, $warning );
1256 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1257 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1258 // Check if $warning is followed by "\n" or the end of the $oldWarning
1259 $warnPos +
= strlen( $warning );
1260 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1264 // If there is a warning already, append it to the existing one
1265 $warning = "$oldWarning\n$warning";
1268 ApiResult
::setContent( $msg, $warning );
1269 $result->addValue( 'warnings', $moduleName,
1270 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1274 * Adds a warning to the output, else dies
1276 * @param string $msg Message to show as a warning, or error message if dying
1277 * @param bool $enforceLimits Whether this is an enforce (die)
1279 private function warnOrDie( $msg, $enforceLimits = false ) {
1280 if ( $enforceLimits ) {
1281 $this->dieUsage( $msg, 'integeroutofrange' );
1284 $this->setWarning( $msg );
1288 * Throw a UsageException, which will (if uncaught) call the main module's
1289 * error handler and die with an error message.
1291 * @param string $description One-line human-readable description of the
1292 * error condition, e.g., "The API requires a valid action parameter"
1293 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1294 * automated identification of the error, e.g., 'unknown_action'
1295 * @param int $httpRespCode HTTP response code
1296 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1297 * @throws UsageException
1299 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1300 throw new UsageException(
1302 $this->encodeParamName( $errorCode ),
1309 * Get error (as code, string) from a Status object.
1312 * @param Status $status
1313 * @return array Array of code and error string
1314 * @throws MWException
1316 public function getErrorFromStatus( $status ) {
1317 if ( $status->isGood() ) {
1318 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1321 $errors = $status->getErrorsArray();
1323 // No errors? Assume the warnings should be treated as errors
1324 $errors = $status->getWarningsArray();
1327 // Still no errors? Punt
1328 $errors = array( array( 'unknownerror-nocode' ) );
1331 // Cannot use dieUsageMsg() because extensions might return custom
1333 if ( $errors[0] instanceof Message
) {
1335 $code = $msg->getKey();
1337 $code = array_shift( $errors[0] );
1338 $msg = wfMessage( $code, $errors[0] );
1340 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1341 // Translate message to code, for backwards compatibility
1342 $code = ApiBase
::$messageMap[$code]['code'];
1345 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1349 * Throw a UsageException based on the errors in the Status object.
1352 * @param Status $status
1353 * @throws MWException
1355 public function dieStatus( $status ) {
1357 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1358 $this->dieUsage( $msg, $code );
1361 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1363 * Array that maps message keys to error messages. $1 and friends are replaced.
1365 public static $messageMap = array(
1366 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1367 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1368 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1370 // Messages from Title::getUserPermissionsErrors()
1371 'ns-specialprotected' => array(
1372 'code' => 'unsupportednamespace',
1373 'info' => "Pages in the Special namespace can't be edited"
1375 'protectedinterface' => array(
1376 'code' => 'protectednamespace-interface',
1377 'info' => "You're not allowed to edit interface messages"
1379 'namespaceprotected' => array(
1380 'code' => 'protectednamespace',
1381 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1383 'customcssprotected' => array(
1384 'code' => 'customcssprotected',
1385 'info' => "You're not allowed to edit custom CSS pages"
1387 'customjsprotected' => array(
1388 'code' => 'customjsprotected',
1389 'info' => "You're not allowed to edit custom JavaScript pages"
1391 'cascadeprotected' => array(
1392 'code' => 'cascadeprotected',
1393 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1395 'protectedpagetext' => array(
1396 'code' => 'protectedpage',
1397 'info' => "The \"\$1\" right is required to edit this page"
1399 'protect-cantedit' => array(
1400 'code' => 'cantedit',
1401 'info' => "You can't protect this page because you can't edit it"
1403 'deleteprotected' => array(
1404 'code' => 'cantedit',
1405 'info' => "You can't delete this page because it has been protected"
1407 'badaccess-group0' => array(
1408 'code' => 'permissiondenied',
1409 'info' => "Permission denied"
1410 ), // Generic permission denied message
1411 'badaccess-groups' => array(
1412 'code' => 'permissiondenied',
1413 'info' => "Permission denied"
1415 'titleprotected' => array(
1416 'code' => 'protectedtitle',
1417 'info' => "This title has been protected from creation"
1419 'nocreate-loggedin' => array(
1420 'code' => 'cantcreate',
1421 'info' => "You don't have permission to create new pages"
1423 'nocreatetext' => array(
1424 'code' => 'cantcreate-anon',
1425 'info' => "Anonymous users can't create new pages"
1427 'movenologintext' => array(
1428 'code' => 'cantmove-anon',
1429 'info' => "Anonymous users can't move pages"
1431 'movenotallowed' => array(
1432 'code' => 'cantmove',
1433 'info' => "You don't have permission to move pages"
1435 'confirmedittext' => array(
1436 'code' => 'confirmemail',
1437 'info' => "You must confirm your email address before you can edit"
1439 'blockedtext' => array(
1440 'code' => 'blocked',
1441 'info' => "You have been blocked from editing"
1443 'autoblockedtext' => array(
1444 'code' => 'autoblocked',
1445 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1448 // Miscellaneous interface messages
1449 'actionthrottledtext' => array(
1450 'code' => 'ratelimited',
1451 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1453 'alreadyrolled' => array(
1454 'code' => 'alreadyrolled',
1455 'info' => "The page you tried to rollback was already rolled back"
1457 'cantrollback' => array(
1458 'code' => 'onlyauthor',
1459 'info' => "The page you tried to rollback only has one author"
1461 'readonlytext' => array(
1462 'code' => 'readonly',
1463 'info' => "The wiki is currently in read-only mode"
1465 'sessionfailure' => array(
1466 'code' => 'badtoken',
1467 'info' => "Invalid token" ),
1468 'cannotdelete' => array(
1469 'code' => 'cantdelete',
1470 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1472 'notanarticle' => array(
1473 'code' => 'missingtitle',
1474 'info' => "The page you requested doesn't exist"
1476 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1478 'immobile_namespace' => array(
1479 'code' => 'immobilenamespace',
1480 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1482 'articleexists' => array(
1483 'code' => 'articleexists',
1484 'info' => "The destination article already exists and is not a redirect to the source article"
1486 'protectedpage' => array(
1487 'code' => 'protectedpage',
1488 'info' => "You don't have permission to perform this move"
1490 'hookaborted' => array(
1491 'code' => 'hookaborted',
1492 'info' => "The modification you tried to make was aborted by an extension hook"
1494 'cantmove-titleprotected' => array(
1495 'code' => 'protectedtitle',
1496 'info' => "The destination article has been protected from creation"
1498 'imagenocrossnamespace' => array(
1499 'code' => 'nonfilenamespace',
1500 'info' => "Can't move a file to a non-file namespace"
1502 'imagetypemismatch' => array(
1503 'code' => 'filetypemismatch',
1504 'info' => "The new file extension doesn't match its type"
1506 // 'badarticleerror' => shouldn't happen
1507 // 'badtitletext' => shouldn't happen
1508 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1509 'range_block_disabled' => array(
1510 'code' => 'rangedisabled',
1511 'info' => "Blocking IP ranges has been disabled"
1513 'nosuchusershort' => array(
1514 'code' => 'nosuchuser',
1515 'info' => "The user you specified doesn't exist"
1517 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1518 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1519 'ipb_already_blocked' => array(
1520 'code' => 'alreadyblocked',
1521 'info' => "The user you tried to block was already blocked"
1523 'ipb_blocked_as_range' => array(
1524 'code' => 'blockedasrange',
1525 '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."
1527 'ipb_cant_unblock' => array(
1528 'code' => 'cantunblock',
1529 'info' => "The block you specified was not found. It may have been unblocked already"
1531 'mailnologin' => array(
1532 'code' => 'cantsend',
1533 '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"
1535 'ipbblocked' => array(
1536 'code' => 'ipbblocked',
1537 'info' => 'You cannot block or unblock users while you are yourself blocked'
1539 'ipbnounblockself' => array(
1540 'code' => 'ipbnounblockself',
1541 'info' => 'You are not allowed to unblock yourself'
1543 'usermaildisabled' => array(
1544 'code' => 'usermaildisabled',
1545 'info' => "User email has been disabled"
1547 'blockedemailuser' => array(
1548 'code' => 'blockedfrommail',
1549 'info' => "You have been blocked from sending email"
1551 'notarget' => array(
1552 'code' => 'notarget',
1553 'info' => "You have not specified a valid target for this action"
1556 'code' => 'noemail',
1557 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1559 'rcpatroldisabled' => array(
1560 'code' => 'patroldisabled',
1561 'info' => "Patrolling is disabled on this wiki"
1563 'markedaspatrollederror-noautopatrol' => array(
1564 'code' => 'noautopatrol',
1565 'info' => "You don't have permission to patrol your own changes"
1567 'delete-toobig' => array(
1568 'code' => 'bigdelete',
1569 'info' => "You can't delete this page because it has more than \$1 revisions"
1571 'movenotallowedfile' => array(
1572 'code' => 'cantmovefile',
1573 'info' => "You don't have permission to move files"
1575 'userrights-no-interwiki' => array(
1576 'code' => 'nointerwikiuserrights',
1577 'info' => "You don't have permission to change user rights on other wikis"
1579 'userrights-nodatabase' => array(
1580 'code' => 'nosuchdatabase',
1581 'info' => "Database \"\$1\" does not exist or is not local"
1583 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1584 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1585 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1586 'import-rootpage-invalid' => array(
1587 'code' => 'import-rootpage-invalid',
1588 'info' => 'Root page is an invalid title'
1590 'import-rootpage-nosubpage' => array(
1591 'code' => 'import-rootpage-nosubpage',
1592 'info' => 'Namespace "$1" of the root page does not allow subpages'
1595 // API-specific messages
1596 'readrequired' => array(
1597 'code' => 'readapidenied',
1598 'info' => "You need read permission to use this module"
1600 'writedisabled' => array(
1601 'code' => 'noapiwrite',
1602 '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"
1604 'writerequired' => array(
1605 'code' => 'writeapidenied',
1606 'info' => "You're not allowed to edit this wiki through the API"
1608 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1609 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1610 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1611 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1612 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1613 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1614 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1615 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1616 'create-titleexists' => array(
1617 'code' => 'create-titleexists',
1618 'info' => "Existing titles can't be protected with 'create'"
1620 'missingtitle-createonly' => array(
1621 'code' => 'missingtitle-createonly',
1622 'info' => "Missing titles can only be protected with 'create'"
1624 'cantblock' => array( 'code' => 'cantblock',
1625 'info' => "You don't have permission to block users"
1627 'canthide' => array(
1628 'code' => 'canthide',
1629 'info' => "You don't have permission to hide user names from the block log"
1631 'cantblock-email' => array(
1632 'code' => 'cantblock-email',
1633 'info' => "You don't have permission to block users from sending email through the wiki"
1635 'unblock-notarget' => array(
1636 'code' => 'notarget',
1637 'info' => "Either the id or the user parameter must be set"
1639 'unblock-idanduser' => array(
1640 'code' => 'idanduser',
1641 'info' => "The id and user parameters can't be used together"
1643 'cantunblock' => array(
1644 'code' => 'permissiondenied',
1645 'info' => "You don't have permission to unblock users"
1647 'cannotundelete' => array(
1648 'code' => 'cantundelete',
1649 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1651 'permdenied-undelete' => array(
1652 'code' => 'permissiondenied',
1653 'info' => "You don't have permission to restore deleted revisions"
1655 'createonly-exists' => array(
1656 'code' => 'articleexists',
1657 'info' => "The article you tried to create has been created already"
1659 'nocreate-missing' => array(
1660 'code' => 'missingtitle',
1661 'info' => "The article you tried to edit doesn't exist"
1663 'cantchangecontentmodel' => array(
1664 'code' => 'cantchangecontentmodel',
1665 'info' => "You don't have permission to change the content model of a page"
1667 'nosuchrcid' => array(
1668 'code' => 'nosuchrcid',
1669 'info' => "There is no change with rcid \"\$1\""
1671 'protect-invalidaction' => array(
1672 'code' => 'protect-invalidaction',
1673 'info' => "Invalid protection type \"\$1\""
1675 'protect-invalidlevel' => array(
1676 'code' => 'protect-invalidlevel',
1677 'info' => "Invalid protection level \"\$1\""
1679 'toofewexpiries' => array(
1680 'code' => 'toofewexpiries',
1681 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1683 'cantimport' => array(
1684 'code' => 'cantimport',
1685 'info' => "You don't have permission to import pages"
1687 'cantimport-upload' => array(
1688 'code' => 'cantimport-upload',
1689 'info' => "You don't have permission to import uploaded pages"
1691 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1692 'importuploaderrorsize' => array(
1693 'code' => 'filetoobig',
1694 'info' => 'The file you uploaded is bigger than the maximum upload size'
1696 'importuploaderrorpartial' => array(
1697 'code' => 'partialupload',
1698 'info' => 'The file was only partially uploaded'
1700 'importuploaderrortemp' => array(
1701 'code' => 'notempdir',
1702 'info' => 'The temporary upload directory is missing'
1704 'importcantopen' => array(
1705 'code' => 'cantopenfile',
1706 'info' => "Couldn't open the uploaded file"
1708 'import-noarticle' => array(
1709 'code' => 'badinterwiki',
1710 'info' => 'Invalid interwiki title specified'
1712 'importbadinterwiki' => array(
1713 'code' => 'badinterwiki',
1714 'info' => 'Invalid interwiki title specified'
1716 'import-unknownerror' => array(
1717 'code' => 'import-unknownerror',
1718 'info' => "Unknown error on import: \"\$1\""
1720 'cantoverwrite-sharedfile' => array(
1721 'code' => 'cantoverwrite-sharedfile',
1722 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1724 'sharedfile-exists' => array(
1725 'code' => 'fileexists-sharedrepo-perm',
1726 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1728 'mustbeposted' => array(
1729 'code' => 'mustbeposted',
1730 'info' => "The \$1 module requires a POST request"
1734 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1736 'specialpage-cantexecute' => array(
1737 'code' => 'specialpage-cantexecute',
1738 'info' => "You don't have permission to view the results of this special page"
1740 'invalidoldimage' => array(
1741 'code' => 'invalidoldimage',
1742 'info' => 'The oldimage parameter has invalid format'
1744 'nodeleteablefile' => array(
1745 'code' => 'nodeleteablefile',
1746 'info' => 'No such old version of the file'
1748 'fileexists-forbidden' => array(
1749 'code' => 'fileexists-forbidden',
1750 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1752 'fileexists-shared-forbidden' => array(
1753 'code' => 'fileexists-shared-forbidden',
1754 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1756 'filerevert-badversion' => array(
1757 'code' => 'filerevert-badversion',
1758 'info' => 'There is no previous local version of this file with the provided timestamp.'
1761 // ApiEditPage messages
1762 'noimageredirect-anon' => array(
1763 'code' => 'noimageredirect-anon',
1764 'info' => "Anonymous users can't create image redirects"
1766 'noimageredirect-logged' => array(
1767 'code' => 'noimageredirect',
1768 'info' => "You don't have permission to create image redirects"
1770 'spamdetected' => array(
1771 'code' => 'spamdetected',
1772 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1774 'contenttoobig' => array(
1775 'code' => 'contenttoobig',
1776 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1778 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1779 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1780 'wasdeleted' => array(
1781 'code' => 'pagedeleted',
1782 'info' => "The page has been deleted since you fetched its timestamp"
1784 'blankpage' => array(
1785 'code' => 'emptypage',
1786 'info' => "Creating new, empty pages is not allowed"
1788 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1789 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1790 'missingtext' => array(
1792 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1794 'emptynewsection' => array(
1795 'code' => 'emptynewsection',
1796 'info' => 'Creating empty new sections is not possible.'
1798 'revwrongpage' => array(
1799 'code' => 'revwrongpage',
1800 'info' => "r\$1 is not a revision of \"\$2\""
1802 'undo-failure' => array(
1803 'code' => 'undofailure',
1804 'info' => 'Undo failed due to conflicting intermediate edits'
1806 'content-not-allowed-here' => array(
1807 'code' => 'contentnotallowedhere',
1808 'info' => 'Content model "$1" is not allowed at title "$2"'
1811 // Messages from WikiPage::doEit()
1812 'edit-hook-aborted' => array(
1813 'code' => 'edit-hook-aborted',
1814 'info' => "Your edit was aborted by an ArticleSave hook"
1816 'edit-gone-missing' => array(
1817 'code' => 'edit-gone-missing',
1818 'info' => "The page you tried to edit doesn't seem to exist anymore"
1820 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1821 'edit-already-exists' => array(
1822 'code' => 'edit-already-exists',
1823 'info' => 'It seems the page you tried to create already exist'
1827 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1828 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1829 'uploaddisabled' => array(
1830 'code' => 'uploaddisabled',
1831 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1833 'copyuploaddisabled' => array(
1834 'code' => 'copyuploaddisabled',
1835 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1837 'copyuploadbaddomain' => array(
1838 'code' => 'copyuploadbaddomain',
1839 'info' => 'Uploads by URL are not allowed from this domain.'
1841 'copyuploadbadurl' => array(
1842 'code' => 'copyuploadbadurl',
1843 'info' => 'Upload not allowed from this URL.'
1846 'filename-tooshort' => array(
1847 'code' => 'filename-tooshort',
1848 'info' => 'The filename is too short'
1850 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1851 'illegal-filename' => array(
1852 'code' => 'illegal-filename',
1853 'info' => 'The filename is not allowed'
1855 'filetype-missing' => array(
1856 'code' => 'filetype-missing',
1857 'info' => 'The file is missing an extension'
1860 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1862 // @codingStandardsIgnoreEnd
1865 * Helper function for readonly errors
1867 public function dieReadOnly() {
1868 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1869 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1870 array( 'readonlyreason' => wfReadOnlyReason() ) );
1874 * Output the error message related to a certain array
1875 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1877 public function dieUsageMsg( $error ) {
1878 # most of the time we send a 1 element, so we might as well send it as
1879 # a string and make this an array here.
1880 if ( is_string( $error ) ) {
1881 $error = array( $error );
1883 $parsed = $this->parseMsg( $error );
1884 $this->dieUsage( $parsed['info'], $parsed['code'] );
1888 * Will only set a warning instead of failing if the global $wgDebugAPI
1889 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1890 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1893 public function dieUsageMsgOrDebug( $error ) {
1894 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1895 $this->dieUsageMsg( $error );
1898 if ( is_string( $error ) ) {
1899 $error = array( $error );
1901 $parsed = $this->parseMsg( $error );
1902 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1906 * Die with the $prefix.'badcontinue' error. This call is common enough to
1907 * make it into the base method.
1908 * @param bool $condition Will only die if this value is true
1911 protected function dieContinueUsageIf( $condition ) {
1914 'Invalid continue param. You should pass the original value returned by the previous query',
1920 * Return the error message related to a certain array
1921 * @param array $error Element of a getUserPermissionsErrors()-style array
1922 * @return array('code' => code, 'info' => info)
1924 public function parseMsg( $error ) {
1925 $error = (array)$error; // It seems strings sometimes make their way in here
1926 $key = array_shift( $error );
1928 // Check whether the error array was nested
1929 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1930 if ( is_array( $key ) ) {
1932 $key = array_shift( $error );
1935 if ( isset( self
::$messageMap[$key] ) ) {
1937 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1938 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1942 // If the key isn't present, throw an "unknown error"
1943 return $this->parseMsg( array( 'unknownerror', $key ) );
1947 * Internal code errors should be reported with this method
1948 * @param string $method Method or function name
1949 * @param string $message Error message
1950 * @throws MWException
1952 protected static function dieDebug( $method, $message ) {
1953 throw new MWException( "Internal error in $method: $message" );
1957 * Write logging information for API features to a debug log, for usage
1959 * @param string $feature Feature being used.
1961 protected function logFeatureUsage( $feature ) {
1962 $request = $this->getRequest();
1963 $s = '"' . addslashes( $feature ) . '"' .
1964 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1965 ' "' . $request->getIP() . '"' .
1966 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1967 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1968 wfDebugLog( 'api-feature-usage', $s, 'private' );
1973 /************************************************************************//**
1974 * @name Help message generation
1979 * Return the description message.
1981 * @return string|array|Message
1983 protected function getDescriptionMessage() {
1984 return "apihelp-{$this->getModulePath()}-description";
1988 * Get final module description, after hooks have had a chance to tweak it as
1991 * @since 1.25, returns Message[] rather than string[]
1994 public function getFinalDescription() {
1995 $desc = $this->getDescription();
1996 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
1997 $desc = self
::escapeWikiText( $desc );
1998 if ( is_array( $desc ) ) {
1999 $desc = join( "\n", $desc );
2001 $desc = (string)$desc;
2004 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2005 $this->getModulePrefix(),
2006 $this->getModuleName(),
2007 $this->getModulePath(),
2009 if ( !$msg->exists() ) {
2010 $msg = $this->msg( 'api-help-fallback-description', $desc );
2012 $msgs = array( $msg );
2014 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2020 * Get final list of parameters, after hooks have had a chance to
2021 * tweak it as needed.
2023 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2024 * @return array|bool False on no parameters
2025 * @since 1.21 $flags param added
2027 public function getFinalParams( $flags = 0 ) {
2028 $params = $this->getAllowedParams( $flags );
2033 if ( $this->needsToken() ) {
2034 $params['token'] = array(
2035 ApiBase
::PARAM_TYPE
=> 'string',
2036 ApiBase
::PARAM_REQUIRED
=> true,
2037 ApiBase
::PARAM_HELP_MSG
=> array(
2038 'api-help-param-token',
2039 $this->needsToken(),
2041 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2044 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2050 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2053 * @since 1.25, returns array of Message[] rather than array of string[]
2054 * @return array Keys are parameter names, values are arrays of Message objects
2056 public function getFinalParamDescription() {
2057 $prefix = $this->getModulePrefix();
2058 $name = $this->getModuleName();
2059 $path = $this->getModulePath();
2061 $desc = $this->getParamDescription();
2062 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2067 $desc = self
::escapeWikiText( $desc );
2069 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2071 foreach ( $params as $param => $settings ) {
2072 if ( !is_array( $settings ) ) {
2073 $settings = array();
2076 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2077 if ( is_array( $d ) ) {
2078 // Special handling for prop parameters
2079 $d = array_map( function ( $line ) {
2080 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2081 $line = "\n;{$m[1]}:{$m[2]}";
2085 $d = join( ' ', $d );
2088 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2089 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2091 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2092 if ( !$msg->exists() ) {
2093 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2096 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2097 array( $prefix, $param, $name, $path ) );
2099 $this->dieDebug( __METHOD__
,
2100 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2102 $msgs[$param] = array( $msg );
2104 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2105 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2106 $this->dieDebug( __METHOD__
,
2107 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2109 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2110 $this->dieDebug( __METHOD__
,
2111 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2112 'ApiBase::PARAM_TYPE is an array' );
2115 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2116 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2117 if ( isset( $valueMsgs[$value] ) ) {
2118 $msg = $valueMsgs[$value];
2120 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2122 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2123 array( $prefix, $param, $name, $path, $value ) );
2125 $m = new ApiHelpParamValueMessage(
2127 array( $m->getKey(), 'api-help-param-no-description' ),
2130 $msgs[$param][] = $m->setContext( $this->getContext() );
2132 $this->dieDebug( __METHOD__
,
2133 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2138 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2139 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2140 $this->dieDebug( __METHOD__
,
2141 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2143 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2144 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2145 array( $prefix, $param, $name, $path ) );
2147 $msgs[$param][] = $m;
2149 $this->dieDebug( __METHOD__
,
2150 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2156 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2162 * Generates the list of flags for the help screen and for action=paraminfo
2164 * Corresponding messages: api-help-flag-deprecated,
2165 * api-help-flag-internal, api-help-flag-readrights,
2166 * api-help-flag-writerights, api-help-flag-mustbeposted
2170 protected function getHelpFlags() {
2173 if ( $this->isDeprecated() ) {
2174 $flags[] = 'deprecated';
2176 if ( $this->isInternal() ) {
2177 $flags[] = 'internal';
2179 if ( $this->isReadMode() ) {
2180 $flags[] = 'readrights';
2182 if ( $this->isWriteMode() ) {
2183 $flags[] = 'writerights';
2185 if ( $this->mustBePosted() ) {
2186 $flags[] = 'mustbeposted';
2193 * Returns information about the source of this module, if known
2195 * Returned array is an array with the following keys:
2196 * - path: Install path
2197 * - name: Extension name, or "MediaWiki" for core
2198 * - namemsg: (optional) i18n message key for a display name
2199 * - license-name: (optional) Name of license
2201 * @return array|null
2203 protected function getModuleSourceInfo() {
2206 if ( $this->mModuleSource
!== false ) {
2207 return $this->mModuleSource
;
2210 // First, try to find where the module comes from...
2211 $rClass = new ReflectionClass( $this );
2212 $path = $rClass->getFileName();
2215 $this->mModuleSource
= null;
2218 $path = realpath( $path ) ?
: $path;
2220 // Build map of extension directories to extension info
2221 if ( self
::$extensionInfo === null ) {
2222 self
::$extensionInfo = array(
2223 realpath( __DIR__
) ?
: __DIR__
=> array(
2225 'name' => 'MediaWiki',
2226 'license-name' => 'GPL-2.0+',
2228 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2234 'license-name' => null,
2236 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2237 foreach ( $group as $ext ) {
2238 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2239 // This shouldn't happen, but does anyway.
2243 $extpath = $ext['path'];
2244 if ( !is_dir( $extpath ) ) {
2245 $extpath = dirname( $extpath );
2247 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2248 array_intersect_key( $ext, $keep );
2251 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2252 $extpath = $ext['path'];
2253 if ( !is_dir( $extpath ) ) {
2254 $extpath = dirname( $extpath );
2256 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2257 array_intersect_key( $ext, $keep );
2261 // Now traverse parent directories until we find a match or run out of
2264 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2266 $this->mModuleSource
= self
::$extensionInfo[$path];
2267 return $this->mModuleSource
;
2271 $path = dirname( $path );
2272 } while ( $path !== $oldpath );
2274 // No idea what extension this might be.
2275 $this->mModuleSource
= null;
2280 * Called from ApiHelp before the pieces are joined together and returned.
2282 * This exists mainly for ApiMain to add the Permissions and Credits
2283 * sections. Other modules probably don't need it.
2285 * @param string[] &$help Array of help data
2286 * @param array $options Options passed to ApiHelp::getHelp
2288 public function modifyHelp( array &$help, array $options ) {
2293 /************************************************************************//**
2298 /// @deprecated since 1.24
2299 const PROP_ROOT
= 'ROOT';
2300 /// @deprecated since 1.24
2301 const PROP_LIST
= 'LIST';
2302 /// @deprecated since 1.24
2303 const PROP_TYPE
= 0;
2304 /// @deprecated since 1.24
2305 const PROP_NULLABLE
= 1;
2308 * Formerly returned a string that identifies the version of the extending
2309 * class. Typically included the class name, the svn revision, timestamp,
2310 * and last author. Usually done with SVN's Id keyword
2312 * @deprecated since 1.21, version string is no longer supported
2315 public function getVersion() {
2316 wfDeprecated( __METHOD__
, '1.21' );
2321 * Formerly used to fetch a list of possible properites in the result,
2322 * somehow organized with respect to the prop parameter that causes them to
2323 * be returned. The specific semantics of the return value was never
2324 * specified. Since this was never possible to be accurately updated, it
2327 * @deprecated since 1.24
2328 * @return array|bool
2330 protected function getResultProperties() {
2331 wfDeprecated( __METHOD__
, '1.24' );
2336 * @see self::getResultProperties()
2337 * @deprecated since 1.24
2338 * @return array|bool
2340 public function getFinalResultProperties() {
2341 wfDeprecated( __METHOD__
, '1.24' );
2346 * @see self::getResultProperties()
2347 * @deprecated since 1.24
2349 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2350 wfDeprecated( __METHOD__
, '1.24' );
2354 * @see self::getPossibleErrors()
2355 * @deprecated since 1.24
2358 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2359 wfDeprecated( __METHOD__
, '1.24' );
2364 * @see self::getPossibleErrors()
2365 * @deprecated since 1.24
2368 public function getRequireMaxOneParameterErrorMessages( $params ) {
2369 wfDeprecated( __METHOD__
, '1.24' );
2374 * @see self::getPossibleErrors()
2375 * @deprecated since 1.24
2378 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2379 wfDeprecated( __METHOD__
, '1.24' );
2384 * @see self::getPossibleErrors()
2385 * @deprecated since 1.24
2388 public function getTitleOrPageIdErrorMessage() {
2389 wfDeprecated( __METHOD__
, '1.24' );
2394 * This formerly attempted to return a list of all possible errors returned
2395 * by the module. However, this was impossible to maintain in many cases
2396 * since errors could come from other areas of MediaWiki and in some cases
2397 * from arbitrary extension hooks. Since a partial list claiming to be
2398 * comprehensive is unlikely to be useful, it was removed.
2400 * @deprecated since 1.24
2403 public function getPossibleErrors() {
2404 wfDeprecated( __METHOD__
, '1.24' );
2409 * @see self::getPossibleErrors()
2410 * @deprecated since 1.24
2413 public function getFinalPossibleErrors() {
2414 wfDeprecated( __METHOD__
, '1.24' );
2419 * @see self::getPossibleErrors()
2420 * @deprecated since 1.24
2423 public function parseErrors( $errors ) {
2424 wfDeprecated( __METHOD__
, '1.24' );
2429 * Returns the description string for this module
2431 * Ignored if an i18n message exists for
2432 * "apihelp-{$this->getModulePathString()}-description".
2434 * @deprecated since 1.25
2435 * @return Message|string|array
2437 protected function getDescription() {
2442 * Returns an array of parameter descriptions.
2444 * For each parameter, ignored if an i18n message exists for the parameter.
2445 * By default that message is
2446 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2447 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2448 * self::getFinalParams().
2450 * @deprecated since 1.25
2451 * @return array|bool False on no parameter descriptions
2453 protected function getParamDescription() {
2458 * Returns usage examples for this module.
2460 * Return value as an array is either:
2461 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2463 * - sequential numeric keys with even-numbered keys being display-text
2464 * and odd-numbered keys being partial urls
2465 * - partial URLs as keys with display-text (string or array-to-be-joined)
2467 * Return value as a string is the same as an array with a numeric key and
2468 * that value, and boolean false means "no examples".
2470 * @deprecated since 1.25, use getExamplesMessages() instead
2471 * @return bool|string|array
2473 protected function getExamples() {
2478 * Generates help message for this module, or false if there is no description
2479 * @deprecated since 1.25
2480 * @return string|bool
2482 public function makeHelpMsg() {
2483 wfDeprecated( __METHOD__
, '1.25' );
2484 static $lnPrfx = "\n ";
2486 $msg = $this->getFinalDescription();
2488 if ( $msg !== false ) {
2490 if ( !is_array( $msg ) ) {
2495 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2497 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2499 if ( $this->isReadMode() ) {
2500 $msg .= "\nThis module requires read rights";
2502 if ( $this->isWriteMode() ) {
2503 $msg .= "\nThis module requires write rights";
2505 if ( $this->mustBePosted() ) {
2506 $msg .= "\nThis module only accepts POST requests";
2508 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2509 $this->mustBePosted()
2515 $paramsMsg = $this->makeHelpMsgParameters();
2516 if ( $paramsMsg !== false ) {
2517 $msg .= "Parameters:\n$paramsMsg";
2520 $examples = $this->getExamples();
2522 if ( !is_array( $examples ) ) {
2527 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2528 foreach ( $examples as $k => $v ) {
2529 if ( is_numeric( $k ) ) {
2532 if ( is_array( $v ) ) {
2533 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2535 $msgExample = " $v";
2538 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2548 * @deprecated since 1.25
2549 * @param string $item
2552 private function indentExampleText( $item ) {
2557 * @deprecated since 1.25
2558 * @param string $prefix Text to split output items
2559 * @param string $title What is being output
2560 * @param string|array $input
2563 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2564 wfDeprecated( __METHOD__
, '1.25' );
2565 if ( $input === false ) {
2568 if ( !is_array( $input ) ) {
2569 $input = array( $input );
2572 if ( count( $input ) > 0 ) {
2574 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2578 $msg .= implode( $prefix, $input ) . "\n";
2587 * Generates the parameter descriptions for this module, to be displayed in the
2589 * @deprecated since 1.25
2590 * @return string|bool
2592 public function makeHelpMsgParameters() {
2593 wfDeprecated( __METHOD__
, '1.25' );
2594 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2597 $paramsDescription = $this->getFinalParamDescription();
2599 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2600 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2601 foreach ( $params as $paramName => $paramSettings ) {
2602 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2603 if ( is_array( $desc ) ) {
2604 $desc = implode( $paramPrefix, $desc );
2608 if ( !is_array( $paramSettings ) ) {
2609 $paramSettings = array(
2610 self
::PARAM_DFLT
=> $paramSettings,
2614 //handle missing type
2615 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2616 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2617 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2619 if ( is_bool( $dflt ) ) {
2620 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2621 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2622 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2623 } elseif ( is_int( $dflt ) ) {
2624 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2628 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2629 && $paramSettings[self
::PARAM_DEPRECATED
]
2631 $desc = "DEPRECATED! $desc";
2634 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2635 && $paramSettings[self
::PARAM_REQUIRED
]
2637 $desc .= $paramPrefix . "This parameter is required";
2640 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2641 ?
$paramSettings[self
::PARAM_TYPE
]
2643 if ( isset( $type ) ) {
2644 $hintPipeSeparated = true;
2645 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2646 ?
$paramSettings[self
::PARAM_ISMULTI
]
2649 $prompt = 'Values (separate with \'|\'): ';
2651 $prompt = 'One value: ';
2654 if ( $type === 'submodule' ) {
2655 $type = $this->getModuleManager()->getNames( $paramName );
2658 if ( is_array( $type ) ) {
2660 $nothingPrompt = '';
2661 foreach ( $type as $t ) {
2663 $nothingPrompt = 'Can be empty, or ';
2668 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2669 $choicesstring = implode( ', ', $choices );
2670 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2671 $hintPipeSeparated = false;
2675 // Special handling because namespaces are
2676 // type-limited, yet they are not given
2677 $desc .= $paramPrefix . $prompt;
2678 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2679 100, $descWordwrap );
2680 $hintPipeSeparated = false;
2683 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2684 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2685 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2687 $desc .= ' allowed';
2690 $s = $multi ?
's' : '';
2691 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2692 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2693 if ( $hasMin ||
$hasMax ) {
2695 $intRangeStr = "The value$s must be no less than " .
2696 "{$paramSettings[self::PARAM_MIN]}";
2697 } elseif ( !$hasMin ) {
2698 $intRangeStr = "The value$s must be no more than " .
2699 "{$paramSettings[self::PARAM_MAX]}";
2701 $intRangeStr = "The value$s must be between " .
2702 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2705 $desc .= $paramPrefix . $intRangeStr;
2709 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2715 if ( $hintPipeSeparated ) {
2716 $desc .= $paramPrefix . "Separate values with '|'";
2719 $isArray = is_array( $type );
2721 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2723 $desc .= $paramPrefix . "Maximum number of values " .
2724 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2729 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2730 if ( !is_null( $default ) && $default !== false ) {
2731 $desc .= $paramPrefix . "Default: $default";
2734 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2744 * @deprecated since 1.25, always returns empty string
2745 * @param DatabaseBase|bool $db
2748 public function getModuleProfileName( $db = false ) {
2749 wfDeprecated( __METHOD__
, '1.25' );
2754 * @deprecated since 1.25
2756 public function profileIn() {
2757 // No wfDeprecated() yet because extensions call this and might need to
2758 // keep doing so for BC.
2762 * @deprecated since 1.25
2764 public function profileOut() {
2765 // No wfDeprecated() yet because extensions call this and might need to
2766 // keep doing so for BC.
2770 * @deprecated since 1.25
2772 public function safeProfileOut() {
2773 wfDeprecated( __METHOD__
, '1.25' );
2777 * @deprecated since 1.25, always returns 0
2780 public function getProfileTime() {
2781 wfDeprecated( __METHOD__
, '1.25' );
2786 * @deprecated since 1.25
2788 public function profileDBIn() {
2789 wfDeprecated( __METHOD__
, '1.25' );
2793 * @deprecated since 1.25
2795 public function profileDBOut() {
2796 wfDeprecated( __METHOD__
, '1.25' );
2800 * @deprecated since 1.25, always returns 0
2803 public function getProfileDBTime() {
2804 wfDeprecated( __METHOD__
, '1.25' );
2812 * For really cool vim folding this needs to be at the end:
2813 * vim: foldmarker=@{,@} foldmethod=marker