5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Specify an alternative i18n message for this help parameter.
69 // Value is $msg for ApiBase::makeMessage()
70 const PARAM_HELP_MSG
= 10;
72 // Specify additional i18n messages to append to the normal message. Value
73 // is an array of $msg for ApiBase::makeMessage()
74 const PARAM_HELP_MSG_APPEND
= 11;
76 // Specify additional information tags for the parameter. Value is an array
77 // of arrays, with the first member being the 'tag' for the info and the
78 // remaining members being the values. In the help, this is formatted using
79 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
80 // comma-joined list of values, $3 = module prefix.
81 const PARAM_HELP_MSG_INFO
= 12;
83 // When PARAM_TYPE is an array, this may be an array mapping those values
84 // to page titles which will be linked in the help.
85 const PARAM_VALUE_LINKS
= 13;
87 // When PARAM_TYPE is an array, this is an array mapping those values to
88 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
89 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
90 const PARAM_HELP_MSG_PER_VALUE
= 14;
92 const LIMIT_BIG1
= 500; // Fast query, std user limit
93 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
94 const LIMIT_SML1
= 50; // Slow query, std user limit
95 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
98 * getAllowedParams() flag: When set, the result could take longer to generate,
99 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
102 const GET_VALUES_FOR_HELP
= 1;
105 private $mMainModule;
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
112 * @param ApiMain $mainModule
113 * @param string $moduleName Name of this module
114 * @param string $modulePrefix Prefix to use for parameter names
116 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
117 $this->mMainModule
= $mainModule;
118 $this->mModuleName
= $moduleName;
119 $this->mModulePrefix
= $modulePrefix;
121 if ( !$this->isMain() ) {
122 $this->setContext( $mainModule->getContext() );
127 /************************************************************************//**
128 * @name Methods to implement
133 * Evaluates the parameters, performs the requested query, and sets up
134 * the result. Concrete implementations of ApiBase must override this
135 * method to provide whatever functionality their module offers.
136 * Implementations must not produce any output on their own and are not
137 * expected to handle any errors.
139 * The execute() method will be invoked directly by ApiMain immediately
140 * before the result of the module is output. Aside from the
141 * constructor, implementations should assume that no other methods
142 * will be called externally on the module before the result is
145 * The result data should be stored in the ApiResult object available
146 * through getResult().
148 abstract public function execute();
151 * Get the module manager, or null if this module has no sub-modules
153 * @return ApiModuleManager
155 public function getModuleManager() {
160 * If the module may only be used with a certain format module,
161 * it should override this method to return an instance of that formatter.
162 * A value of null means the default format will be used.
163 * @note Do not use this just because you don't want to support non-json
164 * formats. This should be used only when there is a fundamental
165 * requirement for a specific format.
166 * @return mixed Instance of a derived class of ApiFormatBase, or null
168 public function getCustomPrinter() {
173 * Returns usage examples for this module.
175 * Return value has query strings as keys, with values being either strings
176 * (message key), arrays (message key + parameter), or Message objects.
178 * Do not call this base class implementation when overriding this method.
183 protected function getExamplesMessages() {
184 // Fall back to old non-localised method
187 $examples = $this->getExamples();
189 if ( !is_array( $examples ) ) {
190 $examples = array( $examples );
191 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
192 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
193 !preg_match( '/^\s*api\.php\?/', $examples[0] )
195 // Fix up the ugly "even numbered elements are description, odd
196 // numbered elemts are the link" format (see doc for self::getExamples)
198 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
199 $tmp[$examples[$i +
1]] = $examples[$i];
204 foreach ( $examples as $k => $v ) {
205 if ( is_numeric( $k ) ) {
210 $msg = self
::escapeWikiText( $v );
211 if ( is_array( $msg ) ) {
212 $msg = join( " ", $msg );
216 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
217 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
225 * Return links to more detailed help pages about the module.
226 * @since 1.25, returning boolean false is deprecated
227 * @return string|array
229 public function getHelpUrls() {
234 * Returns an array of allowed parameters (parameter name) => (default
235 * value) or (parameter name) => (array with PARAM_* constants as keys)
236 * Don't call this function directly: use getFinalParams() to allow
237 * hooks to modify parameters as needed.
239 * Some derived classes may choose to handle an integer $flags parameter
240 * in the overriding methods. Callers of this method can pass zero or
241 * more OR-ed flags like GET_VALUES_FOR_HELP.
245 protected function getAllowedParams( /* $flags = 0 */ ) {
246 // int $flags is not declared because it causes "Strict standards"
247 // warning. Most derived classes do not implement it.
252 * Indicates if this module needs maxlag to be checked
255 public function shouldCheckMaxlag() {
260 * Indicates whether this module requires read rights
263 public function isReadMode() {
268 * Indicates whether this module requires write mode
271 public function isWriteMode() {
276 * Indicates whether this module must be called with a POST request
279 public function mustBePosted() {
280 return $this->needsToken() !== false;
284 * Indicates whether this module is deprecated
288 public function isDeprecated() {
293 * Indicates whether this module is "internal"
294 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
298 public function isInternal() {
303 * Returns the token type this module requires in order to execute.
305 * Modules are strongly encouraged to use the core 'csrf' type unless they
306 * have specialized security needs. If the token type is not one of the
307 * core types, you must use the ApiQueryTokensRegisterTypes hook to
310 * Returning a non-falsey value here will force the addition of an
311 * appropriate 'token' parameter in self::getFinalParams(). Also,
312 * self::mustBePosted() must return true when tokens are used.
314 * In previous versions of MediaWiki, true was a valid return value.
315 * Returning true will generate errors indicating that the API module needs
318 * @return string|false
320 public function needsToken() {
325 * Fetch the salt used in the Web UI corresponding to this module.
327 * Only override this if the Web UI uses a token with a non-constant salt.
330 * @param array $params All supplied parameters for the module
331 * @return string|array|null
333 protected function getWebUITokenSalt( array $params ) {
339 /************************************************************************//**
340 * @name Data access methods
345 * Get the name of the module being executed by this instance
348 public function getModuleName() {
349 return $this->mModuleName
;
353 * Get parameter prefix (usually two letters or an empty string).
356 public function getModulePrefix() {
357 return $this->mModulePrefix
;
361 * Get the main module
364 public function getMain() {
365 return $this->mMainModule
;
369 * Returns true if this module is the main module ($this === $this->mMainModule),
373 public function isMain() {
374 return $this === $this->mMainModule
;
378 * Get the parent of this module
380 * @return ApiBase|null
382 public function getParent() {
383 return $this->isMain() ?
null : $this->getMain();
387 * Returns true if the current request breaks the same-origin policy.
389 * For example, json with callbacks.
391 * https://en.wikipedia.org/wiki/Same-origin_policy
396 public function lacksSameOriginSecurity() {
397 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
401 * Get the path to this module
406 public function getModulePath() {
407 if ( $this->isMain() ) {
409 } elseif ( $this->getParent()->isMain() ) {
410 return $this->getModuleName();
412 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
417 * Get a module from its module path
420 * @param string $path
421 * @return ApiBase|null
422 * @throws UsageException
424 public function getModuleFromPath( $path ) {
425 $module = $this->getMain();
426 if ( $path === 'main' ) {
430 $parts = explode( '+', $path );
431 if ( count( $parts ) === 1 ) {
432 // In case the '+' was typed into URL, it resolves as a space
433 $parts = explode( ' ', $path );
436 $count = count( $parts );
437 for ( $i = 0; $i < $count; $i++
) {
439 $manager = $parent->getModuleManager();
440 if ( $manager === null ) {
441 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
442 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
444 $module = $manager->getModule( $parts[$i] );
446 if ( $module === null ) {
447 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
449 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
459 * Get the result object
462 public function getResult() {
463 // Main module has getResult() method overridden
464 // Safety - avoid infinite loop:
465 if ( $this->isMain() ) {
466 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
469 return $this->getMain()->getResult();
473 * Get the result data array (read-only)
476 public function getResultData() {
477 return $this->getResult()->getData();
481 * Gets a default slave database connection object
482 * @return DatabaseBase
484 protected function getDB() {
485 if ( !isset( $this->mSlaveDB
) ) {
486 $this->profileDBIn();
487 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
488 $this->profileDBOut();
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 Profiler
::instance()->close();
1301 throw new UsageException(
1303 $this->encodeParamName( $errorCode ),
1310 * Get error (as code, string) from a Status object.
1313 * @param Status $status
1314 * @return array Array of code and error string
1315 * @throws MWException
1317 public function getErrorFromStatus( $status ) {
1318 if ( $status->isGood() ) {
1319 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1322 $errors = $status->getErrorsArray();
1324 // No errors? Assume the warnings should be treated as errors
1325 $errors = $status->getWarningsArray();
1328 // Still no errors? Punt
1329 $errors = array( array( 'unknownerror-nocode' ) );
1332 // Cannot use dieUsageMsg() because extensions might return custom
1334 if ( $errors[0] instanceof Message
) {
1336 $code = $msg->getKey();
1338 $code = array_shift( $errors[0] );
1339 $msg = wfMessage( $code, $errors[0] );
1341 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1342 // Translate message to code, for backwards compatibility
1343 $code = ApiBase
::$messageMap[$code]['code'];
1346 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1350 * Throw a UsageException based on the errors in the Status object.
1353 * @param Status $status
1354 * @throws MWException
1356 public function dieStatus( $status ) {
1358 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1359 $this->dieUsage( $msg, $code );
1362 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1364 * Array that maps message keys to error messages. $1 and friends are replaced.
1366 public static $messageMap = array(
1367 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1368 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1369 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1371 // Messages from Title::getUserPermissionsErrors()
1372 'ns-specialprotected' => array(
1373 'code' => 'unsupportednamespace',
1374 'info' => "Pages in the Special namespace can't be edited"
1376 'protectedinterface' => array(
1377 'code' => 'protectednamespace-interface',
1378 'info' => "You're not allowed to edit interface messages"
1380 'namespaceprotected' => array(
1381 'code' => 'protectednamespace',
1382 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1384 'customcssprotected' => array(
1385 'code' => 'customcssprotected',
1386 'info' => "You're not allowed to edit custom CSS pages"
1388 'customjsprotected' => array(
1389 'code' => 'customjsprotected',
1390 'info' => "You're not allowed to edit custom JavaScript pages"
1392 'cascadeprotected' => array(
1393 'code' => 'cascadeprotected',
1394 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1396 'protectedpagetext' => array(
1397 'code' => 'protectedpage',
1398 'info' => "The \"\$1\" right is required to edit this page"
1400 'protect-cantedit' => array(
1401 'code' => 'cantedit',
1402 'info' => "You can't protect this page because you can't edit it"
1404 'deleteprotected' => array(
1405 'code' => 'cantedit',
1406 'info' => "You can't delete this page because it has been protected"
1408 'badaccess-group0' => array(
1409 'code' => 'permissiondenied',
1410 'info' => "Permission denied"
1411 ), // Generic permission denied message
1412 'badaccess-groups' => array(
1413 'code' => 'permissiondenied',
1414 'info' => "Permission denied"
1416 'titleprotected' => array(
1417 'code' => 'protectedtitle',
1418 'info' => "This title has been protected from creation"
1420 'nocreate-loggedin' => array(
1421 'code' => 'cantcreate',
1422 'info' => "You don't have permission to create new pages"
1424 'nocreatetext' => array(
1425 'code' => 'cantcreate-anon',
1426 'info' => "Anonymous users can't create new pages"
1428 'movenologintext' => array(
1429 'code' => 'cantmove-anon',
1430 'info' => "Anonymous users can't move pages"
1432 'movenotallowed' => array(
1433 'code' => 'cantmove',
1434 'info' => "You don't have permission to move pages"
1436 'confirmedittext' => array(
1437 'code' => 'confirmemail',
1438 'info' => "You must confirm your email address before you can edit"
1440 'blockedtext' => array(
1441 'code' => 'blocked',
1442 'info' => "You have been blocked from editing"
1444 'autoblockedtext' => array(
1445 'code' => 'autoblocked',
1446 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1449 // Miscellaneous interface messages
1450 'actionthrottledtext' => array(
1451 'code' => 'ratelimited',
1452 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1454 'alreadyrolled' => array(
1455 'code' => 'alreadyrolled',
1456 'info' => "The page you tried to rollback was already rolled back"
1458 'cantrollback' => array(
1459 'code' => 'onlyauthor',
1460 'info' => "The page you tried to rollback only has one author"
1462 'readonlytext' => array(
1463 'code' => 'readonly',
1464 'info' => "The wiki is currently in read-only mode"
1466 'sessionfailure' => array(
1467 'code' => 'badtoken',
1468 'info' => "Invalid token" ),
1469 'cannotdelete' => array(
1470 'code' => 'cantdelete',
1471 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1473 'notanarticle' => array(
1474 'code' => 'missingtitle',
1475 'info' => "The page you requested doesn't exist"
1477 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1479 'immobile_namespace' => array(
1480 'code' => 'immobilenamespace',
1481 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1483 'articleexists' => array(
1484 'code' => 'articleexists',
1485 'info' => "The destination article already exists and is not a redirect to the source article"
1487 'protectedpage' => array(
1488 'code' => 'protectedpage',
1489 'info' => "You don't have permission to perform this move"
1491 'hookaborted' => array(
1492 'code' => 'hookaborted',
1493 'info' => "The modification you tried to make was aborted by an extension hook"
1495 'cantmove-titleprotected' => array(
1496 'code' => 'protectedtitle',
1497 'info' => "The destination article has been protected from creation"
1499 'imagenocrossnamespace' => array(
1500 'code' => 'nonfilenamespace',
1501 'info' => "Can't move a file to a non-file namespace"
1503 'imagetypemismatch' => array(
1504 'code' => 'filetypemismatch',
1505 'info' => "The new file extension doesn't match its type"
1507 // 'badarticleerror' => shouldn't happen
1508 // 'badtitletext' => shouldn't happen
1509 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1510 'range_block_disabled' => array(
1511 'code' => 'rangedisabled',
1512 'info' => "Blocking IP ranges has been disabled"
1514 'nosuchusershort' => array(
1515 'code' => 'nosuchuser',
1516 'info' => "The user you specified doesn't exist"
1518 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1519 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1520 'ipb_already_blocked' => array(
1521 'code' => 'alreadyblocked',
1522 'info' => "The user you tried to block was already blocked"
1524 'ipb_blocked_as_range' => array(
1525 'code' => 'blockedasrange',
1526 '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."
1528 'ipb_cant_unblock' => array(
1529 'code' => 'cantunblock',
1530 'info' => "The block you specified was not found. It may have been unblocked already"
1532 'mailnologin' => array(
1533 'code' => 'cantsend',
1534 '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"
1536 'ipbblocked' => array(
1537 'code' => 'ipbblocked',
1538 'info' => 'You cannot block or unblock users while you are yourself blocked'
1540 'ipbnounblockself' => array(
1541 'code' => 'ipbnounblockself',
1542 'info' => 'You are not allowed to unblock yourself'
1544 'usermaildisabled' => array(
1545 'code' => 'usermaildisabled',
1546 'info' => "User email has been disabled"
1548 'blockedemailuser' => array(
1549 'code' => 'blockedfrommail',
1550 'info' => "You have been blocked from sending email"
1552 'notarget' => array(
1553 'code' => 'notarget',
1554 'info' => "You have not specified a valid target for this action"
1557 'code' => 'noemail',
1558 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1560 'rcpatroldisabled' => array(
1561 'code' => 'patroldisabled',
1562 'info' => "Patrolling is disabled on this wiki"
1564 'markedaspatrollederror-noautopatrol' => array(
1565 'code' => 'noautopatrol',
1566 'info' => "You don't have permission to patrol your own changes"
1568 'delete-toobig' => array(
1569 'code' => 'bigdelete',
1570 'info' => "You can't delete this page because it has more than \$1 revisions"
1572 'movenotallowedfile' => array(
1573 'code' => 'cantmovefile',
1574 'info' => "You don't have permission to move files"
1576 'userrights-no-interwiki' => array(
1577 'code' => 'nointerwikiuserrights',
1578 'info' => "You don't have permission to change user rights on other wikis"
1580 'userrights-nodatabase' => array(
1581 'code' => 'nosuchdatabase',
1582 'info' => "Database \"\$1\" does not exist or is not local"
1584 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1585 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1586 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1587 'import-rootpage-invalid' => array(
1588 'code' => 'import-rootpage-invalid',
1589 'info' => 'Root page is an invalid title'
1591 'import-rootpage-nosubpage' => array(
1592 'code' => 'import-rootpage-nosubpage',
1593 'info' => 'Namespace "$1" of the root page does not allow subpages'
1596 // API-specific messages
1597 'readrequired' => array(
1598 'code' => 'readapidenied',
1599 'info' => "You need read permission to use this module"
1601 'writedisabled' => array(
1602 'code' => 'noapiwrite',
1603 '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"
1605 'writerequired' => array(
1606 'code' => 'writeapidenied',
1607 'info' => "You're not allowed to edit this wiki through the API"
1609 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1610 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1611 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1612 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1613 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1614 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1615 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1616 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1617 'create-titleexists' => array(
1618 'code' => 'create-titleexists',
1619 'info' => "Existing titles can't be protected with 'create'"
1621 'missingtitle-createonly' => array(
1622 'code' => 'missingtitle-createonly',
1623 'info' => "Missing titles can only be protected with 'create'"
1625 'cantblock' => array( 'code' => 'cantblock',
1626 'info' => "You don't have permission to block users"
1628 'canthide' => array(
1629 'code' => 'canthide',
1630 'info' => "You don't have permission to hide user names from the block log"
1632 'cantblock-email' => array(
1633 'code' => 'cantblock-email',
1634 'info' => "You don't have permission to block users from sending email through the wiki"
1636 'unblock-notarget' => array(
1637 'code' => 'notarget',
1638 'info' => "Either the id or the user parameter must be set"
1640 'unblock-idanduser' => array(
1641 'code' => 'idanduser',
1642 'info' => "The id and user parameters can't be used together"
1644 'cantunblock' => array(
1645 'code' => 'permissiondenied',
1646 'info' => "You don't have permission to unblock users"
1648 'cannotundelete' => array(
1649 'code' => 'cantundelete',
1650 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1652 'permdenied-undelete' => array(
1653 'code' => 'permissiondenied',
1654 'info' => "You don't have permission to restore deleted revisions"
1656 'createonly-exists' => array(
1657 'code' => 'articleexists',
1658 'info' => "The article you tried to create has been created already"
1660 'nocreate-missing' => array(
1661 'code' => 'missingtitle',
1662 'info' => "The article you tried to edit doesn't exist"
1664 'cantchangecontentmodel' => array(
1665 'code' => 'cantchangecontentmodel',
1666 'info' => "You don't have permission to change the content model of a page"
1668 'nosuchrcid' => array(
1669 'code' => 'nosuchrcid',
1670 'info' => "There is no change with rcid \"\$1\""
1672 'protect-invalidaction' => array(
1673 'code' => 'protect-invalidaction',
1674 'info' => "Invalid protection type \"\$1\""
1676 'protect-invalidlevel' => array(
1677 'code' => 'protect-invalidlevel',
1678 'info' => "Invalid protection level \"\$1\""
1680 'toofewexpiries' => array(
1681 'code' => 'toofewexpiries',
1682 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1684 'cantimport' => array(
1685 'code' => 'cantimport',
1686 'info' => "You don't have permission to import pages"
1688 'cantimport-upload' => array(
1689 'code' => 'cantimport-upload',
1690 'info' => "You don't have permission to import uploaded pages"
1692 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1693 'importuploaderrorsize' => array(
1694 'code' => 'filetoobig',
1695 'info' => 'The file you uploaded is bigger than the maximum upload size'
1697 'importuploaderrorpartial' => array(
1698 'code' => 'partialupload',
1699 'info' => 'The file was only partially uploaded'
1701 'importuploaderrortemp' => array(
1702 'code' => 'notempdir',
1703 'info' => 'The temporary upload directory is missing'
1705 'importcantopen' => array(
1706 'code' => 'cantopenfile',
1707 'info' => "Couldn't open the uploaded file"
1709 'import-noarticle' => array(
1710 'code' => 'badinterwiki',
1711 'info' => 'Invalid interwiki title specified'
1713 'importbadinterwiki' => array(
1714 'code' => 'badinterwiki',
1715 'info' => 'Invalid interwiki title specified'
1717 'import-unknownerror' => array(
1718 'code' => 'import-unknownerror',
1719 'info' => "Unknown error on import: \"\$1\""
1721 'cantoverwrite-sharedfile' => array(
1722 'code' => 'cantoverwrite-sharedfile',
1723 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1725 'sharedfile-exists' => array(
1726 'code' => 'fileexists-sharedrepo-perm',
1727 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1729 'mustbeposted' => array(
1730 'code' => 'mustbeposted',
1731 'info' => "The \$1 module requires a POST request"
1735 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1737 'specialpage-cantexecute' => array(
1738 'code' => 'specialpage-cantexecute',
1739 'info' => "You don't have permission to view the results of this special page"
1741 'invalidoldimage' => array(
1742 'code' => 'invalidoldimage',
1743 'info' => 'The oldimage parameter has invalid format'
1745 'nodeleteablefile' => array(
1746 'code' => 'nodeleteablefile',
1747 'info' => 'No such old version of the file'
1749 'fileexists-forbidden' => array(
1750 'code' => 'fileexists-forbidden',
1751 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1753 'fileexists-shared-forbidden' => array(
1754 'code' => 'fileexists-shared-forbidden',
1755 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1757 'filerevert-badversion' => array(
1758 'code' => 'filerevert-badversion',
1759 'info' => 'There is no previous local version of this file with the provided timestamp.'
1762 // ApiEditPage messages
1763 'noimageredirect-anon' => array(
1764 'code' => 'noimageredirect-anon',
1765 'info' => "Anonymous users can't create image redirects"
1767 'noimageredirect-logged' => array(
1768 'code' => 'noimageredirect',
1769 'info' => "You don't have permission to create image redirects"
1771 'spamdetected' => array(
1772 'code' => 'spamdetected',
1773 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1775 'contenttoobig' => array(
1776 'code' => 'contenttoobig',
1777 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1779 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1780 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1781 'wasdeleted' => array(
1782 'code' => 'pagedeleted',
1783 'info' => "The page has been deleted since you fetched its timestamp"
1785 'blankpage' => array(
1786 'code' => 'emptypage',
1787 'info' => "Creating new, empty pages is not allowed"
1789 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1790 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1791 'missingtext' => array(
1793 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1795 'emptynewsection' => array(
1796 'code' => 'emptynewsection',
1797 'info' => 'Creating empty new sections is not possible.'
1799 'revwrongpage' => array(
1800 'code' => 'revwrongpage',
1801 'info' => "r\$1 is not a revision of \"\$2\""
1803 'undo-failure' => array(
1804 'code' => 'undofailure',
1805 'info' => 'Undo failed due to conflicting intermediate edits'
1807 'content-not-allowed-here' => array(
1808 'code' => 'contentnotallowedhere',
1809 'info' => 'Content model "$1" is not allowed at title "$2"'
1812 // Messages from WikiPage::doEit()
1813 'edit-hook-aborted' => array(
1814 'code' => 'edit-hook-aborted',
1815 'info' => "Your edit was aborted by an ArticleSave hook"
1817 'edit-gone-missing' => array(
1818 'code' => 'edit-gone-missing',
1819 'info' => "The page you tried to edit doesn't seem to exist anymore"
1821 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1822 'edit-already-exists' => array(
1823 'code' => 'edit-already-exists',
1824 'info' => 'It seems the page you tried to create already exist'
1828 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1829 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1830 'uploaddisabled' => array(
1831 'code' => 'uploaddisabled',
1832 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1834 'copyuploaddisabled' => array(
1835 'code' => 'copyuploaddisabled',
1836 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1838 'copyuploadbaddomain' => array(
1839 'code' => 'copyuploadbaddomain',
1840 'info' => 'Uploads by URL are not allowed from this domain.'
1842 'copyuploadbadurl' => array(
1843 'code' => 'copyuploadbadurl',
1844 'info' => 'Upload not allowed from this URL.'
1847 'filename-tooshort' => array(
1848 'code' => 'filename-tooshort',
1849 'info' => 'The filename is too short'
1851 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1852 'illegal-filename' => array(
1853 'code' => 'illegal-filename',
1854 'info' => 'The filename is not allowed'
1856 'filetype-missing' => array(
1857 'code' => 'filetype-missing',
1858 'info' => 'The file is missing an extension'
1861 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1863 // @codingStandardsIgnoreEnd
1866 * Helper function for readonly errors
1868 public function dieReadOnly() {
1869 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1870 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1871 array( 'readonlyreason' => wfReadOnlyReason() ) );
1875 * Output the error message related to a certain array
1876 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1878 public function dieUsageMsg( $error ) {
1879 # most of the time we send a 1 element, so we might as well send it as
1880 # a string and make this an array here.
1881 if ( is_string( $error ) ) {
1882 $error = array( $error );
1884 $parsed = $this->parseMsg( $error );
1885 $this->dieUsage( $parsed['info'], $parsed['code'] );
1889 * Will only set a warning instead of failing if the global $wgDebugAPI
1890 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1891 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1894 public function dieUsageMsgOrDebug( $error ) {
1895 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1896 $this->dieUsageMsg( $error );
1899 if ( is_string( $error ) ) {
1900 $error = array( $error );
1902 $parsed = $this->parseMsg( $error );
1903 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1907 * Die with the $prefix.'badcontinue' error. This call is common enough to
1908 * make it into the base method.
1909 * @param bool $condition Will only die if this value is true
1912 protected function dieContinueUsageIf( $condition ) {
1915 'Invalid continue param. You should pass the original value returned by the previous query',
1921 * Return the error message related to a certain array
1922 * @param array $error Element of a getUserPermissionsErrors()-style array
1923 * @return array('code' => code, 'info' => info)
1925 public function parseMsg( $error ) {
1926 $error = (array)$error; // It seems strings sometimes make their way in here
1927 $key = array_shift( $error );
1929 // Check whether the error array was nested
1930 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1931 if ( is_array( $key ) ) {
1933 $key = array_shift( $error );
1936 if ( isset( self
::$messageMap[$key] ) ) {
1938 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1939 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1943 // If the key isn't present, throw an "unknown error"
1944 return $this->parseMsg( array( 'unknownerror', $key ) );
1948 * Internal code errors should be reported with this method
1949 * @param string $method Method or function name
1950 * @param string $message Error message
1951 * @throws MWException
1953 protected static function dieDebug( $method, $message ) {
1954 throw new MWException( "Internal error in $method: $message" );
1959 /************************************************************************//**
1960 * @name Help message generation
1965 * Return the description message.
1967 * @return string|array|Message
1969 protected function getDescriptionMessage() {
1970 return "apihelp-{$this->getModulePath()}-description";
1974 * Get final module description, after hooks have had a chance to tweak it as
1977 * @since 1.25, returns Message[] rather than string[]
1980 public function getFinalDescription() {
1981 $desc = $this->getDescription();
1982 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
1983 $desc = self
::escapeWikiText( $desc );
1984 if ( is_array( $desc ) ) {
1985 $desc = join( "\n", $desc );
1987 $desc = (string)$desc;
1990 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1991 $this->getModulePrefix(),
1992 $this->getModuleName(),
1993 $this->getModulePath(),
1995 if ( !$msg->exists() ) {
1996 $msg = $this->msg( 'api-help-fallback-description', $desc );
1998 $msgs = array( $msg );
2000 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2006 * Get final list of parameters, after hooks have had a chance to
2007 * tweak it as needed.
2009 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2010 * @return array|bool False on no parameters
2011 * @since 1.21 $flags param added
2013 public function getFinalParams( $flags = 0 ) {
2014 $params = $this->getAllowedParams( $flags );
2019 if ( $this->needsToken() ) {
2020 $params['token'] = array(
2021 ApiBase
::PARAM_TYPE
=> 'string',
2022 ApiBase
::PARAM_REQUIRED
=> true,
2023 ApiBase
::PARAM_HELP_MSG
=> array(
2024 'api-help-param-token',
2025 $this->needsToken(),
2027 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2030 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2036 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2039 * @since 1.25, returns array of Message[] rather than array of string[]
2040 * @return array Keys are parameter names, values are arrays of Message objects
2042 public function getFinalParamDescription() {
2043 $prefix = $this->getModulePrefix();
2044 $name = $this->getModuleName();
2045 $path = $this->getModulePath();
2047 $desc = $this->getParamDescription();
2048 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2053 $desc = self
::escapeWikiText( $desc );
2055 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2057 foreach ( $params as $param => $settings ) {
2058 if ( !is_array( $settings ) ) {
2059 $settings = array();
2062 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2063 if ( is_array( $d ) ) {
2064 // Special handling for prop parameters
2065 $d = array_map( function ( $line ) {
2066 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2067 $line = "\n;{$m[1]}:{$m[2]}";
2071 $d = join( ' ', $d );
2074 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2075 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2077 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2078 if ( !$msg->exists() ) {
2079 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2082 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2083 array( $prefix, $param, $name, $path ) );
2085 $this->dieDebug( __METHOD__
,
2086 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2088 $msgs[$param] = array( $msg );
2090 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2091 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2092 $this->dieDebug( __METHOD__
,
2093 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2095 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2096 $this->dieDebug( __METHOD__
,
2097 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2098 'ApiBase::PARAM_TYPE is an array' );
2101 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2102 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2103 if ( isset( $valueMsgs[$value] ) ) {
2104 $msg = $valueMsgs[$value];
2106 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2108 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2109 array( $prefix, $param, $name, $path, $value ) );
2111 $m = new ApiHelpParamValueMessage(
2113 array( $m->getKey(), 'api-help-param-no-description' ),
2116 $msgs[$param][] = $m->setContext( $this->getContext() );
2118 $this->dieDebug( __METHOD__
,
2119 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2124 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2125 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2126 $this->dieDebug( __METHOD__
,
2127 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2129 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2130 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2131 array( $prefix, $param, $name, $path ) );
2133 $msgs[$param][] = $m;
2135 $this->dieDebug( __METHOD__
,
2136 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2142 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2148 * Generates the list of flags for the help screen and for action=paraminfo
2150 * Corresponding messages: api-help-flag-deprecated,
2151 * api-help-flag-internal, api-help-flag-readrights,
2152 * api-help-flag-writerights, api-help-flag-mustbeposted
2156 protected function getHelpFlags() {
2159 if ( $this->isDeprecated() ) {
2160 $flags[] = 'deprecated';
2162 if ( $this->isInternal() ) {
2163 $flags[] = 'internal';
2165 if ( $this->isReadMode() ) {
2166 $flags[] = 'readrights';
2168 if ( $this->isWriteMode() ) {
2169 $flags[] = 'writerights';
2171 if ( $this->mustBePosted() ) {
2172 $flags[] = 'mustbeposted';
2179 * Called from ApiHelp before the pieces are joined together and returned.
2181 * This exists mainly for ApiMain to add the Permissions and Credits
2182 * sections. Other modules probably don't need it.
2184 * @param string[] &$help Array of help data
2185 * @param array $options Options passed to ApiHelp::getHelp
2187 public function modifyHelp( array &$help, array $options ) {
2192 /************************************************************************//**
2198 * Profiling: total module execution time
2200 private $mTimeIn = 0, $mModuleTime = 0;
2201 /** @var ScopedCallback */
2203 /** @var ScopedCallback */
2207 * Get the name of the module as shown in the profiler log
2209 * @param DatabaseBase|bool $db
2213 public function getModuleProfileName( $db = false ) {
2215 return 'API:' . $this->mModuleName
. '-DB';
2218 return 'API:' . $this->mModuleName
;
2222 * Start module profiling
2224 public function profileIn() {
2225 if ( $this->mTimeIn
!== 0 ) {
2226 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2228 $this->mTimeIn
= microtime( true );
2229 $this->profile
= Profiler
::instance()->scopedProfileIn( $this->getModuleProfileName() );
2233 * End module profiling
2235 public function profileOut() {
2236 if ( $this->mTimeIn
=== 0 ) {
2237 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2239 if ( $this->mDBTimeIn
!== 0 ) {
2242 'Must be called after database profiling is done with profileDBOut()'
2246 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2248 Profiler
::instance()->scopedProfileOut( $this->profile
);
2252 * When modules crash, sometimes it is needed to do a profileOut() regardless
2253 * of the profiling state the module was in. This method does such cleanup.
2255 public function safeProfileOut() {
2256 if ( $this->mTimeIn
!== 0 ) {
2257 if ( $this->mDBTimeIn
!== 0 ) {
2258 $this->profileDBOut();
2260 $this->profileOut();
2265 * Total time the module was executed
2268 public function getProfileTime() {
2269 if ( $this->mTimeIn
!== 0 ) {
2270 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2273 return $this->mModuleTime
;
2277 * Profiling: database execution time
2279 private $mDBTimeIn = 0, $mDBTime = 0;
2282 * Start module profiling
2284 public function profileDBIn() {
2285 if ( $this->mTimeIn
=== 0 ) {
2288 'Must be called while profiling the entire module with profileIn()'
2291 if ( $this->mDBTimeIn
!== 0 ) {
2292 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2294 $this->mDBTimeIn
= microtime( true );
2296 $this->dbProfile
= Profiler
::instance()->scopedProfileIn( $this->getModuleProfileName( true ) );
2300 * End database profiling
2302 public function profileDBOut() {
2303 if ( $this->mTimeIn
=== 0 ) {
2304 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2305 'the entire module with profileIn()' );
2307 if ( $this->mDBTimeIn
=== 0 ) {
2308 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2311 $time = microtime( true ) - $this->mDBTimeIn
;
2312 $this->mDBTimeIn
= 0;
2314 $this->mDBTime +
= $time;
2315 $this->getMain()->mDBTime +
= $time;
2316 Profiler
::instance()->scopedProfileOut( $this->dbProfile
);
2320 * Total time the module used the database
2323 public function getProfileDBTime() {
2324 if ( $this->mDBTimeIn
!== 0 ) {
2325 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2328 return $this->mDBTime
;
2332 * Write logging information for API features to a debug log, for usage
2334 * @param string $feature Feature being used.
2336 protected function logFeatureUsage( $feature ) {
2337 $request = $this->getRequest();
2338 $s = '"' . addslashes( $feature ) . '"' .
2339 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2340 ' "' . $request->getIP() . '"' .
2341 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2342 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2343 wfDebugLog( 'api-feature-usage', $s, 'private' );
2348 /************************************************************************//**
2353 /// @deprecated since 1.24
2354 const PROP_ROOT
= 'ROOT';
2355 /// @deprecated since 1.24
2356 const PROP_LIST
= 'LIST';
2357 /// @deprecated since 1.24
2358 const PROP_TYPE
= 0;
2359 /// @deprecated since 1.24
2360 const PROP_NULLABLE
= 1;
2363 * Formerly returned a string that identifies the version of the extending
2364 * class. Typically included the class name, the svn revision, timestamp,
2365 * and last author. Usually done with SVN's Id keyword
2367 * @deprecated since 1.21, version string is no longer supported
2370 public function getVersion() {
2371 wfDeprecated( __METHOD__
, '1.21' );
2376 * Formerly used to fetch a list of possible properites in the result,
2377 * somehow organized with respect to the prop parameter that causes them to
2378 * be returned. The specific semantics of the return value was never
2379 * specified. Since this was never possible to be accurately updated, it
2382 * @deprecated since 1.24
2383 * @return array|bool
2385 protected function getResultProperties() {
2386 wfDeprecated( __METHOD__
, '1.24' );
2391 * @see self::getResultProperties()
2392 * @deprecated since 1.24
2393 * @return array|bool
2395 public function getFinalResultProperties() {
2396 wfDeprecated( __METHOD__
, '1.24' );
2401 * @see self::getResultProperties()
2402 * @deprecated since 1.24
2404 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2405 wfDeprecated( __METHOD__
, '1.24' );
2409 * @see self::getPossibleErrors()
2410 * @deprecated since 1.24
2413 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2414 wfDeprecated( __METHOD__
, '1.24' );
2419 * @see self::getPossibleErrors()
2420 * @deprecated since 1.24
2423 public function getRequireMaxOneParameterErrorMessages( $params ) {
2424 wfDeprecated( __METHOD__
, '1.24' );
2429 * @see self::getPossibleErrors()
2430 * @deprecated since 1.24
2433 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2434 wfDeprecated( __METHOD__
, '1.24' );
2439 * @see self::getPossibleErrors()
2440 * @deprecated since 1.24
2443 public function getTitleOrPageIdErrorMessage() {
2444 wfDeprecated( __METHOD__
, '1.24' );
2449 * This formerly attempted to return a list of all possible errors returned
2450 * by the module. However, this was impossible to maintain in many cases
2451 * since errors could come from other areas of MediaWiki and in some cases
2452 * from arbitrary extension hooks. Since a partial list claiming to be
2453 * comprehensive is unlikely to be useful, it was removed.
2455 * @deprecated since 1.24
2458 public function getPossibleErrors() {
2459 wfDeprecated( __METHOD__
, '1.24' );
2464 * @see self::getPossibleErrors()
2465 * @deprecated since 1.24
2468 public function getFinalPossibleErrors() {
2469 wfDeprecated( __METHOD__
, '1.24' );
2474 * @see self::getPossibleErrors()
2475 * @deprecated since 1.24
2478 public function parseErrors( $errors ) {
2479 wfDeprecated( __METHOD__
, '1.24' );
2484 * Returns the description string for this module
2486 * Ignored if an i18n message exists for
2487 * "apihelp-{$this->getModulePathString()}-description".
2489 * @deprecated since 1.25
2490 * @return Message|string|array
2492 protected function getDescription() {
2497 * Returns an array of parameter descriptions.
2499 * For each parameter, ignored if an i18n message exists for the parameter.
2500 * By default that message is
2501 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2502 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2503 * self::getFinalParams().
2505 * @deprecated since 1.25
2506 * @return array|bool False on no parameter descriptions
2508 protected function getParamDescription() {
2513 * Returns usage examples for this module.
2515 * Return value as an array is either:
2516 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2518 * - sequential numeric keys with even-numbered keys being display-text
2519 * and odd-numbered keys being partial urls
2520 * - partial URLs as keys with display-text (string or array-to-be-joined)
2522 * Return value as a string is the same as an array with a numeric key and
2523 * that value, and boolean false means "no examples".
2525 * @deprecated since 1.25, use getExamplesMessages() instead
2526 * @return bool|string|array
2528 protected function getExamples() {
2533 * Generates help message for this module, or false if there is no description
2534 * @deprecated since 1.25
2535 * @return string|bool
2537 public function makeHelpMsg() {
2538 wfDeprecated( __METHOD__
, '1.25' );
2539 static $lnPrfx = "\n ";
2541 $msg = $this->getFinalDescription();
2543 if ( $msg !== false ) {
2545 if ( !is_array( $msg ) ) {
2550 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2552 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2554 if ( $this->isReadMode() ) {
2555 $msg .= "\nThis module requires read rights";
2557 if ( $this->isWriteMode() ) {
2558 $msg .= "\nThis module requires write rights";
2560 if ( $this->mustBePosted() ) {
2561 $msg .= "\nThis module only accepts POST requests";
2563 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2564 $this->mustBePosted()
2570 $paramsMsg = $this->makeHelpMsgParameters();
2571 if ( $paramsMsg !== false ) {
2572 $msg .= "Parameters:\n$paramsMsg";
2575 $examples = $this->getExamples();
2577 if ( !is_array( $examples ) ) {
2582 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2583 foreach ( $examples as $k => $v ) {
2584 if ( is_numeric( $k ) ) {
2587 if ( is_array( $v ) ) {
2588 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2590 $msgExample = " $v";
2593 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2603 * @deprecated since 1.25
2604 * @param string $item
2607 private function indentExampleText( $item ) {
2612 * @deprecated since 1.25
2613 * @param string $prefix Text to split output items
2614 * @param string $title What is being output
2615 * @param string|array $input
2618 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2619 wfDeprecated( __METHOD__
, '1.25' );
2620 if ( $input === false ) {
2623 if ( !is_array( $input ) ) {
2624 $input = array( $input );
2627 if ( count( $input ) > 0 ) {
2629 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2633 $msg .= implode( $prefix, $input ) . "\n";
2642 * Generates the parameter descriptions for this module, to be displayed in the
2644 * @deprecated since 1.25
2645 * @return string|bool
2647 public function makeHelpMsgParameters() {
2648 wfDeprecated( __METHOD__
, '1.25' );
2649 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2652 $paramsDescription = $this->getFinalParamDescription();
2654 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2655 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2656 foreach ( $params as $paramName => $paramSettings ) {
2657 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2658 if ( is_array( $desc ) ) {
2659 $desc = implode( $paramPrefix, $desc );
2663 if ( !is_array( $paramSettings ) ) {
2664 $paramSettings = array(
2665 self
::PARAM_DFLT
=> $paramSettings,
2669 //handle missing type
2670 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2671 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2672 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2674 if ( is_bool( $dflt ) ) {
2675 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2676 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2677 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2678 } elseif ( is_int( $dflt ) ) {
2679 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2683 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2684 && $paramSettings[self
::PARAM_DEPRECATED
]
2686 $desc = "DEPRECATED! $desc";
2689 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2690 && $paramSettings[self
::PARAM_REQUIRED
]
2692 $desc .= $paramPrefix . "This parameter is required";
2695 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2696 ?
$paramSettings[self
::PARAM_TYPE
]
2698 if ( isset( $type ) ) {
2699 $hintPipeSeparated = true;
2700 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2701 ?
$paramSettings[self
::PARAM_ISMULTI
]
2704 $prompt = 'Values (separate with \'|\'): ';
2706 $prompt = 'One value: ';
2709 if ( $type === 'submodule' ) {
2710 $type = $this->getModuleManager()->getNames( $paramName );
2713 if ( is_array( $type ) ) {
2715 $nothingPrompt = '';
2716 foreach ( $type as $t ) {
2718 $nothingPrompt = 'Can be empty, or ';
2723 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2724 $choicesstring = implode( ', ', $choices );
2725 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2726 $hintPipeSeparated = false;
2730 // Special handling because namespaces are
2731 // type-limited, yet they are not given
2732 $desc .= $paramPrefix . $prompt;
2733 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2734 100, $descWordwrap );
2735 $hintPipeSeparated = false;
2738 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2739 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2740 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2742 $desc .= ' allowed';
2745 $s = $multi ?
's' : '';
2746 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2747 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2748 if ( $hasMin ||
$hasMax ) {
2750 $intRangeStr = "The value$s must be no less than " .
2751 "{$paramSettings[self::PARAM_MIN]}";
2752 } elseif ( !$hasMin ) {
2753 $intRangeStr = "The value$s must be no more than " .
2754 "{$paramSettings[self::PARAM_MAX]}";
2756 $intRangeStr = "The value$s must be between " .
2757 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2760 $desc .= $paramPrefix . $intRangeStr;
2764 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2770 if ( $hintPipeSeparated ) {
2771 $desc .= $paramPrefix . "Separate values with '|'";
2774 $isArray = is_array( $type );
2776 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2778 $desc .= $paramPrefix . "Maximum number of values " .
2779 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2784 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2785 if ( !is_null( $default ) && $default !== false ) {
2786 $desc .= $paramPrefix . "Default: $default";
2789 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2802 * For really cool vim folding this needs to be at the end:
2803 * vim: foldmarker=@{,@} foldmethod=marker