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 'nosuchlogid' => array(
1672 'code' => 'nosuchlogid',
1673 'info' => "There is no log entry with ID \"\$1\""
1675 'protect-invalidaction' => array(
1676 'code' => 'protect-invalidaction',
1677 'info' => "Invalid protection type \"\$1\""
1679 'protect-invalidlevel' => array(
1680 'code' => 'protect-invalidlevel',
1681 'info' => "Invalid protection level \"\$1\""
1683 'toofewexpiries' => array(
1684 'code' => 'toofewexpiries',
1685 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1687 'cantimport' => array(
1688 'code' => 'cantimport',
1689 'info' => "You don't have permission to import pages"
1691 'cantimport-upload' => array(
1692 'code' => 'cantimport-upload',
1693 'info' => "You don't have permission to import uploaded pages"
1695 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1696 'importuploaderrorsize' => array(
1697 'code' => 'filetoobig',
1698 'info' => 'The file you uploaded is bigger than the maximum upload size'
1700 'importuploaderrorpartial' => array(
1701 'code' => 'partialupload',
1702 'info' => 'The file was only partially uploaded'
1704 'importuploaderrortemp' => array(
1705 'code' => 'notempdir',
1706 'info' => 'The temporary upload directory is missing'
1708 'importcantopen' => array(
1709 'code' => 'cantopenfile',
1710 'info' => "Couldn't open the uploaded file"
1712 'import-noarticle' => array(
1713 'code' => 'badinterwiki',
1714 'info' => 'Invalid interwiki title specified'
1716 'importbadinterwiki' => array(
1717 'code' => 'badinterwiki',
1718 'info' => 'Invalid interwiki title specified'
1720 'import-unknownerror' => array(
1721 'code' => 'import-unknownerror',
1722 'info' => "Unknown error on import: \"\$1\""
1724 'cantoverwrite-sharedfile' => array(
1725 'code' => 'cantoverwrite-sharedfile',
1726 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1728 'sharedfile-exists' => array(
1729 'code' => 'fileexists-sharedrepo-perm',
1730 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1732 'mustbeposted' => array(
1733 'code' => 'mustbeposted',
1734 'info' => "The \$1 module requires a POST request"
1738 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1740 'specialpage-cantexecute' => array(
1741 'code' => 'specialpage-cantexecute',
1742 'info' => "You don't have permission to view the results of this special page"
1744 'invalidoldimage' => array(
1745 'code' => 'invalidoldimage',
1746 'info' => 'The oldimage parameter has invalid format'
1748 'nodeleteablefile' => array(
1749 'code' => 'nodeleteablefile',
1750 'info' => 'No such old version of the file'
1752 'fileexists-forbidden' => array(
1753 'code' => 'fileexists-forbidden',
1754 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1756 'fileexists-shared-forbidden' => array(
1757 'code' => 'fileexists-shared-forbidden',
1758 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1760 'filerevert-badversion' => array(
1761 'code' => 'filerevert-badversion',
1762 'info' => 'There is no previous local version of this file with the provided timestamp.'
1765 // ApiEditPage messages
1766 'noimageredirect-anon' => array(
1767 'code' => 'noimageredirect-anon',
1768 'info' => "Anonymous users can't create image redirects"
1770 'noimageredirect-logged' => array(
1771 'code' => 'noimageredirect',
1772 'info' => "You don't have permission to create image redirects"
1774 'spamdetected' => array(
1775 'code' => 'spamdetected',
1776 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1778 'contenttoobig' => array(
1779 'code' => 'contenttoobig',
1780 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1782 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1783 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1784 'wasdeleted' => array(
1785 'code' => 'pagedeleted',
1786 'info' => "The page has been deleted since you fetched its timestamp"
1788 'blankpage' => array(
1789 'code' => 'emptypage',
1790 'info' => "Creating new, empty pages is not allowed"
1792 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1793 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1794 'missingtext' => array(
1796 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1798 'emptynewsection' => array(
1799 'code' => 'emptynewsection',
1800 'info' => 'Creating empty new sections is not possible.'
1802 'revwrongpage' => array(
1803 'code' => 'revwrongpage',
1804 'info' => "r\$1 is not a revision of \"\$2\""
1806 'undo-failure' => array(
1807 'code' => 'undofailure',
1808 'info' => 'Undo failed due to conflicting intermediate edits'
1810 'content-not-allowed-here' => array(
1811 'code' => 'contentnotallowedhere',
1812 'info' => 'Content model "$1" is not allowed at title "$2"'
1815 // Messages from WikiPage::doEit()
1816 'edit-hook-aborted' => array(
1817 'code' => 'edit-hook-aborted',
1818 'info' => "Your edit was aborted by an ArticleSave hook"
1820 'edit-gone-missing' => array(
1821 'code' => 'edit-gone-missing',
1822 'info' => "The page you tried to edit doesn't seem to exist anymore"
1824 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1825 'edit-already-exists' => array(
1826 'code' => 'edit-already-exists',
1827 'info' => 'It seems the page you tried to create already exist'
1831 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1832 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1833 'uploaddisabled' => array(
1834 'code' => 'uploaddisabled',
1835 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1837 'copyuploaddisabled' => array(
1838 'code' => 'copyuploaddisabled',
1839 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1841 'copyuploadbaddomain' => array(
1842 'code' => 'copyuploadbaddomain',
1843 'info' => 'Uploads by URL are not allowed from this domain.'
1845 'copyuploadbadurl' => array(
1846 'code' => 'copyuploadbadurl',
1847 'info' => 'Upload not allowed from this URL.'
1850 'filename-tooshort' => array(
1851 'code' => 'filename-tooshort',
1852 'info' => 'The filename is too short'
1854 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1855 'illegal-filename' => array(
1856 'code' => 'illegal-filename',
1857 'info' => 'The filename is not allowed'
1859 'filetype-missing' => array(
1860 'code' => 'filetype-missing',
1861 'info' => 'The file is missing an extension'
1864 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1866 // @codingStandardsIgnoreEnd
1869 * Helper function for readonly errors
1871 public function dieReadOnly() {
1872 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1873 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1874 array( 'readonlyreason' => wfReadOnlyReason() ) );
1878 * Output the error message related to a certain array
1879 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1881 public function dieUsageMsg( $error ) {
1882 # most of the time we send a 1 element, so we might as well send it as
1883 # a string and make this an array here.
1884 if ( is_string( $error ) ) {
1885 $error = array( $error );
1887 $parsed = $this->parseMsg( $error );
1888 $this->dieUsage( $parsed['info'], $parsed['code'] );
1892 * Will only set a warning instead of failing if the global $wgDebugAPI
1893 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1894 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1897 public function dieUsageMsgOrDebug( $error ) {
1898 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1899 $this->dieUsageMsg( $error );
1902 if ( is_string( $error ) ) {
1903 $error = array( $error );
1905 $parsed = $this->parseMsg( $error );
1906 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1910 * Die with the $prefix.'badcontinue' error. This call is common enough to
1911 * make it into the base method.
1912 * @param bool $condition Will only die if this value is true
1915 protected function dieContinueUsageIf( $condition ) {
1918 'Invalid continue param. You should pass the original value returned by the previous query',
1924 * Return the error message related to a certain array
1925 * @param array $error Element of a getUserPermissionsErrors()-style array
1926 * @return array('code' => code, 'info' => info)
1928 public function parseMsg( $error ) {
1929 $error = (array)$error; // It seems strings sometimes make their way in here
1930 $key = array_shift( $error );
1932 // Check whether the error array was nested
1933 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1934 if ( is_array( $key ) ) {
1936 $key = array_shift( $error );
1939 if ( isset( self
::$messageMap[$key] ) ) {
1941 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1942 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1946 // If the key isn't present, throw an "unknown error"
1947 return $this->parseMsg( array( 'unknownerror', $key ) );
1951 * Internal code errors should be reported with this method
1952 * @param string $method Method or function name
1953 * @param string $message Error message
1954 * @throws MWException
1956 protected static function dieDebug( $method, $message ) {
1957 throw new MWException( "Internal error in $method: $message" );
1961 * Write logging information for API features to a debug log, for usage
1963 * @param string $feature Feature being used.
1965 protected function logFeatureUsage( $feature ) {
1966 $request = $this->getRequest();
1967 $s = '"' . addslashes( $feature ) . '"' .
1968 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1969 ' "' . $request->getIP() . '"' .
1970 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1971 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1972 wfDebugLog( 'api-feature-usage', $s, 'private' );
1977 /************************************************************************//**
1978 * @name Help message generation
1983 * Return the description message.
1985 * @return string|array|Message
1987 protected function getDescriptionMessage() {
1988 return "apihelp-{$this->getModulePath()}-description";
1992 * Get final module description, after hooks have had a chance to tweak it as
1995 * @since 1.25, returns Message[] rather than string[]
1998 public function getFinalDescription() {
1999 $desc = $this->getDescription();
2000 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2001 $desc = self
::escapeWikiText( $desc );
2002 if ( is_array( $desc ) ) {
2003 $desc = join( "\n", $desc );
2005 $desc = (string)$desc;
2008 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2009 $this->getModulePrefix(),
2010 $this->getModuleName(),
2011 $this->getModulePath(),
2013 if ( !$msg->exists() ) {
2014 $msg = $this->msg( 'api-help-fallback-description', $desc );
2016 $msgs = array( $msg );
2018 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2024 * Get final list of parameters, after hooks have had a chance to
2025 * tweak it as needed.
2027 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2028 * @return array|bool False on no parameters
2029 * @since 1.21 $flags param added
2031 public function getFinalParams( $flags = 0 ) {
2032 $params = $this->getAllowedParams( $flags );
2037 if ( $this->needsToken() ) {
2038 $params['token'] = array(
2039 ApiBase
::PARAM_TYPE
=> 'string',
2040 ApiBase
::PARAM_REQUIRED
=> true,
2041 ApiBase
::PARAM_HELP_MSG
=> array(
2042 'api-help-param-token',
2043 $this->needsToken(),
2045 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2048 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2054 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2057 * @since 1.25, returns array of Message[] rather than array of string[]
2058 * @return array Keys are parameter names, values are arrays of Message objects
2060 public function getFinalParamDescription() {
2061 $prefix = $this->getModulePrefix();
2062 $name = $this->getModuleName();
2063 $path = $this->getModulePath();
2065 $desc = $this->getParamDescription();
2066 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2071 $desc = self
::escapeWikiText( $desc );
2073 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2075 foreach ( $params as $param => $settings ) {
2076 if ( !is_array( $settings ) ) {
2077 $settings = array();
2080 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2081 if ( is_array( $d ) ) {
2082 // Special handling for prop parameters
2083 $d = array_map( function ( $line ) {
2084 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2085 $line = "\n;{$m[1]}:{$m[2]}";
2089 $d = join( ' ', $d );
2092 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2093 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2095 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2096 if ( !$msg->exists() ) {
2097 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2100 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2101 array( $prefix, $param, $name, $path ) );
2103 $this->dieDebug( __METHOD__
,
2104 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2106 $msgs[$param] = array( $msg );
2108 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2109 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2110 $this->dieDebug( __METHOD__
,
2111 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2113 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2114 $this->dieDebug( __METHOD__
,
2115 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2116 'ApiBase::PARAM_TYPE is an array' );
2119 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2120 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2121 if ( isset( $valueMsgs[$value] ) ) {
2122 $msg = $valueMsgs[$value];
2124 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2126 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2127 array( $prefix, $param, $name, $path, $value ) );
2129 $m = new ApiHelpParamValueMessage(
2131 array( $m->getKey(), 'api-help-param-no-description' ),
2134 $msgs[$param][] = $m->setContext( $this->getContext() );
2136 $this->dieDebug( __METHOD__
,
2137 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2142 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2143 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2144 $this->dieDebug( __METHOD__
,
2145 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2147 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2148 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2149 array( $prefix, $param, $name, $path ) );
2151 $msgs[$param][] = $m;
2153 $this->dieDebug( __METHOD__
,
2154 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2160 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2166 * Generates the list of flags for the help screen and for action=paraminfo
2168 * Corresponding messages: api-help-flag-deprecated,
2169 * api-help-flag-internal, api-help-flag-readrights,
2170 * api-help-flag-writerights, api-help-flag-mustbeposted
2174 protected function getHelpFlags() {
2177 if ( $this->isDeprecated() ) {
2178 $flags[] = 'deprecated';
2180 if ( $this->isInternal() ) {
2181 $flags[] = 'internal';
2183 if ( $this->isReadMode() ) {
2184 $flags[] = 'readrights';
2186 if ( $this->isWriteMode() ) {
2187 $flags[] = 'writerights';
2189 if ( $this->mustBePosted() ) {
2190 $flags[] = 'mustbeposted';
2197 * Returns information about the source of this module, if known
2199 * Returned array is an array with the following keys:
2200 * - path: Install path
2201 * - name: Extension name, or "MediaWiki" for core
2202 * - namemsg: (optional) i18n message key for a display name
2203 * - license-name: (optional) Name of license
2205 * @return array|null
2207 protected function getModuleSourceInfo() {
2210 if ( $this->mModuleSource
!== false ) {
2211 return $this->mModuleSource
;
2214 // First, try to find where the module comes from...
2215 $rClass = new ReflectionClass( $this );
2216 $path = $rClass->getFileName();
2219 $this->mModuleSource
= null;
2222 $path = realpath( $path ) ?
: $path;
2224 // Build map of extension directories to extension info
2225 if ( self
::$extensionInfo === null ) {
2226 self
::$extensionInfo = array(
2227 realpath( __DIR__
) ?
: __DIR__
=> array(
2229 'name' => 'MediaWiki',
2230 'license-name' => 'GPL-2.0+',
2232 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2238 'license-name' => null,
2240 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2241 foreach ( $group as $ext ) {
2242 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2243 // This shouldn't happen, but does anyway.
2247 $extpath = $ext['path'];
2248 if ( !is_dir( $extpath ) ) {
2249 $extpath = dirname( $extpath );
2251 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2252 array_intersect_key( $ext, $keep );
2255 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2256 $extpath = $ext['path'];
2257 if ( !is_dir( $extpath ) ) {
2258 $extpath = dirname( $extpath );
2260 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2261 array_intersect_key( $ext, $keep );
2265 // Now traverse parent directories until we find a match or run out of
2268 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2270 $this->mModuleSource
= self
::$extensionInfo[$path];
2271 return $this->mModuleSource
;
2275 $path = dirname( $path );
2276 } while ( $path !== $oldpath );
2278 // No idea what extension this might be.
2279 $this->mModuleSource
= null;
2284 * Called from ApiHelp before the pieces are joined together and returned.
2286 * This exists mainly for ApiMain to add the Permissions and Credits
2287 * sections. Other modules probably don't need it.
2289 * @param string[] &$help Array of help data
2290 * @param array $options Options passed to ApiHelp::getHelp
2292 public function modifyHelp( array &$help, array $options ) {
2297 /************************************************************************//**
2302 /// @deprecated since 1.24
2303 const PROP_ROOT
= 'ROOT';
2304 /// @deprecated since 1.24
2305 const PROP_LIST
= 'LIST';
2306 /// @deprecated since 1.24
2307 const PROP_TYPE
= 0;
2308 /// @deprecated since 1.24
2309 const PROP_NULLABLE
= 1;
2312 * Formerly returned a string that identifies the version of the extending
2313 * class. Typically included the class name, the svn revision, timestamp,
2314 * and last author. Usually done with SVN's Id keyword
2316 * @deprecated since 1.21, version string is no longer supported
2319 public function getVersion() {
2320 wfDeprecated( __METHOD__
, '1.21' );
2325 * Formerly used to fetch a list of possible properites in the result,
2326 * somehow organized with respect to the prop parameter that causes them to
2327 * be returned. The specific semantics of the return value was never
2328 * specified. Since this was never possible to be accurately updated, it
2331 * @deprecated since 1.24
2332 * @return array|bool
2334 protected function getResultProperties() {
2335 wfDeprecated( __METHOD__
, '1.24' );
2340 * @see self::getResultProperties()
2341 * @deprecated since 1.24
2342 * @return array|bool
2344 public function getFinalResultProperties() {
2345 wfDeprecated( __METHOD__
, '1.24' );
2350 * @see self::getResultProperties()
2351 * @deprecated since 1.24
2353 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2354 wfDeprecated( __METHOD__
, '1.24' );
2358 * @see self::getPossibleErrors()
2359 * @deprecated since 1.24
2362 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2363 wfDeprecated( __METHOD__
, '1.24' );
2368 * @see self::getPossibleErrors()
2369 * @deprecated since 1.24
2372 public function getRequireMaxOneParameterErrorMessages( $params ) {
2373 wfDeprecated( __METHOD__
, '1.24' );
2378 * @see self::getPossibleErrors()
2379 * @deprecated since 1.24
2382 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2383 wfDeprecated( __METHOD__
, '1.24' );
2388 * @see self::getPossibleErrors()
2389 * @deprecated since 1.24
2392 public function getTitleOrPageIdErrorMessage() {
2393 wfDeprecated( __METHOD__
, '1.24' );
2398 * This formerly attempted to return a list of all possible errors returned
2399 * by the module. However, this was impossible to maintain in many cases
2400 * since errors could come from other areas of MediaWiki and in some cases
2401 * from arbitrary extension hooks. Since a partial list claiming to be
2402 * comprehensive is unlikely to be useful, it was removed.
2404 * @deprecated since 1.24
2407 public function getPossibleErrors() {
2408 wfDeprecated( __METHOD__
, '1.24' );
2413 * @see self::getPossibleErrors()
2414 * @deprecated since 1.24
2417 public function getFinalPossibleErrors() {
2418 wfDeprecated( __METHOD__
, '1.24' );
2423 * @see self::getPossibleErrors()
2424 * @deprecated since 1.24
2427 public function parseErrors( $errors ) {
2428 wfDeprecated( __METHOD__
, '1.24' );
2433 * Returns the description string for this module
2435 * Ignored if an i18n message exists for
2436 * "apihelp-{$this->getModulePathString()}-description".
2438 * @deprecated since 1.25
2439 * @return Message|string|array
2441 protected function getDescription() {
2446 * Returns an array of parameter descriptions.
2448 * For each parameter, ignored if an i18n message exists for the parameter.
2449 * By default that message is
2450 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2451 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2452 * self::getFinalParams().
2454 * @deprecated since 1.25
2455 * @return array|bool False on no parameter descriptions
2457 protected function getParamDescription() {
2462 * Returns usage examples for this module.
2464 * Return value as an array is either:
2465 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2467 * - sequential numeric keys with even-numbered keys being display-text
2468 * and odd-numbered keys being partial urls
2469 * - partial URLs as keys with display-text (string or array-to-be-joined)
2471 * Return value as a string is the same as an array with a numeric key and
2472 * that value, and boolean false means "no examples".
2474 * @deprecated since 1.25, use getExamplesMessages() instead
2475 * @return bool|string|array
2477 protected function getExamples() {
2482 * Generates help message for this module, or false if there is no description
2483 * @deprecated since 1.25
2484 * @return string|bool
2486 public function makeHelpMsg() {
2487 wfDeprecated( __METHOD__
, '1.25' );
2488 static $lnPrfx = "\n ";
2490 $msg = $this->getFinalDescription();
2492 if ( $msg !== false ) {
2494 if ( !is_array( $msg ) ) {
2499 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2501 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2503 if ( $this->isReadMode() ) {
2504 $msg .= "\nThis module requires read rights";
2506 if ( $this->isWriteMode() ) {
2507 $msg .= "\nThis module requires write rights";
2509 if ( $this->mustBePosted() ) {
2510 $msg .= "\nThis module only accepts POST requests";
2512 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2513 $this->mustBePosted()
2519 $paramsMsg = $this->makeHelpMsgParameters();
2520 if ( $paramsMsg !== false ) {
2521 $msg .= "Parameters:\n$paramsMsg";
2524 $examples = $this->getExamples();
2526 if ( !is_array( $examples ) ) {
2531 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2532 foreach ( $examples as $k => $v ) {
2533 if ( is_numeric( $k ) ) {
2536 if ( is_array( $v ) ) {
2537 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2539 $msgExample = " $v";
2542 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2552 * @deprecated since 1.25
2553 * @param string $item
2556 private function indentExampleText( $item ) {
2561 * @deprecated since 1.25
2562 * @param string $prefix Text to split output items
2563 * @param string $title What is being output
2564 * @param string|array $input
2567 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2568 wfDeprecated( __METHOD__
, '1.25' );
2569 if ( $input === false ) {
2572 if ( !is_array( $input ) ) {
2573 $input = array( $input );
2576 if ( count( $input ) > 0 ) {
2578 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2582 $msg .= implode( $prefix, $input ) . "\n";
2591 * Generates the parameter descriptions for this module, to be displayed in the
2593 * @deprecated since 1.25
2594 * @return string|bool
2596 public function makeHelpMsgParameters() {
2597 wfDeprecated( __METHOD__
, '1.25' );
2598 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2601 $paramsDescription = $this->getFinalParamDescription();
2603 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2604 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2605 foreach ( $params as $paramName => $paramSettings ) {
2606 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2607 if ( is_array( $desc ) ) {
2608 $desc = implode( $paramPrefix, $desc );
2612 if ( !is_array( $paramSettings ) ) {
2613 $paramSettings = array(
2614 self
::PARAM_DFLT
=> $paramSettings,
2618 //handle missing type
2619 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2620 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2621 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2623 if ( is_bool( $dflt ) ) {
2624 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2625 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2626 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2627 } elseif ( is_int( $dflt ) ) {
2628 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2632 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2633 && $paramSettings[self
::PARAM_DEPRECATED
]
2635 $desc = "DEPRECATED! $desc";
2638 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2639 && $paramSettings[self
::PARAM_REQUIRED
]
2641 $desc .= $paramPrefix . "This parameter is required";
2644 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2645 ?
$paramSettings[self
::PARAM_TYPE
]
2647 if ( isset( $type ) ) {
2648 $hintPipeSeparated = true;
2649 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2650 ?
$paramSettings[self
::PARAM_ISMULTI
]
2653 $prompt = 'Values (separate with \'|\'): ';
2655 $prompt = 'One value: ';
2658 if ( $type === 'submodule' ) {
2659 $type = $this->getModuleManager()->getNames( $paramName );
2662 if ( is_array( $type ) ) {
2664 $nothingPrompt = '';
2665 foreach ( $type as $t ) {
2667 $nothingPrompt = 'Can be empty, or ';
2672 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2673 $choicesstring = implode( ', ', $choices );
2674 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2675 $hintPipeSeparated = false;
2679 // Special handling because namespaces are
2680 // type-limited, yet they are not given
2681 $desc .= $paramPrefix . $prompt;
2682 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2683 100, $descWordwrap );
2684 $hintPipeSeparated = false;
2687 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2688 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2689 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2691 $desc .= ' allowed';
2694 $s = $multi ?
's' : '';
2695 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2696 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2697 if ( $hasMin ||
$hasMax ) {
2699 $intRangeStr = "The value$s must be no less than " .
2700 "{$paramSettings[self::PARAM_MIN]}";
2701 } elseif ( !$hasMin ) {
2702 $intRangeStr = "The value$s must be no more than " .
2703 "{$paramSettings[self::PARAM_MAX]}";
2705 $intRangeStr = "The value$s must be between " .
2706 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2709 $desc .= $paramPrefix . $intRangeStr;
2713 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2719 if ( $hintPipeSeparated ) {
2720 $desc .= $paramPrefix . "Separate values with '|'";
2723 $isArray = is_array( $type );
2725 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2727 $desc .= $paramPrefix . "Maximum number of values " .
2728 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2733 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2734 if ( !is_null( $default ) && $default !== false ) {
2735 $desc .= $paramPrefix . "Default: $default";
2738 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2748 * @deprecated since 1.25, always returns empty string
2749 * @param DatabaseBase|bool $db
2752 public function getModuleProfileName( $db = false ) {
2753 wfDeprecated( __METHOD__
, '1.25' );
2758 * @deprecated since 1.25
2760 public function profileIn() {
2761 // No wfDeprecated() yet because extensions call this and might need to
2762 // keep doing so for BC.
2766 * @deprecated since 1.25
2768 public function profileOut() {
2769 // No wfDeprecated() yet because extensions call this and might need to
2770 // keep doing so for BC.
2774 * @deprecated since 1.25
2776 public function safeProfileOut() {
2777 wfDeprecated( __METHOD__
, '1.25' );
2781 * @deprecated since 1.25, always returns 0
2784 public function getProfileTime() {
2785 wfDeprecated( __METHOD__
, '1.25' );
2790 * @deprecated since 1.25
2792 public function profileDBIn() {
2793 wfDeprecated( __METHOD__
, '1.25' );
2797 * @deprecated since 1.25
2799 public function profileDBOut() {
2800 wfDeprecated( __METHOD__
, '1.25' );
2804 * @deprecated since 1.25, always returns 0
2807 public function getProfileDBTime() {
2808 wfDeprecated( __METHOD__
, '1.25' );
2816 * For really cool vim folding this needs to be at the end:
2817 * vim: foldmarker=@{,@} foldmethod=marker