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 error formatter
476 * @return ApiErrorFormatter
478 public function getErrorFormatter() {
479 // Main module has getErrorFormatter() method overridden
480 // Safety - avoid infinite loop:
481 if ( $this->isMain() ) {
482 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
485 return $this->getMain()->getErrorFormatter();
489 * Gets a default slave database connection object
490 * @return DatabaseBase
492 protected function getDB() {
493 if ( !isset( $this->mSlaveDB
) ) {
494 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
497 return $this->mSlaveDB
;
501 * Get the continuation manager
502 * @return ApiContinuationManager|null
504 public function getContinuationManager() {
505 // Main module has getContinuationManager() method overridden
506 // Safety - avoid infinite loop:
507 if ( $this->isMain() ) {
508 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
511 return $this->getMain()->getContinuationManager();
515 * Set the continuation manager
516 * @param ApiContinuationManager|null
518 public function setContinuationManager( $manager ) {
519 // Main module has setContinuationManager() method overridden
520 // Safety - avoid infinite loop:
521 if ( $this->isMain() ) {
522 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
525 $this->getMain()->setContinuationManager( $manager );
530 /************************************************************************//**
531 * @name Parameter handling
536 * This method mangles parameter name based on the prefix supplied to the constructor.
537 * Override this method to change parameter name during runtime
538 * @param string $paramName Parameter name
539 * @return string Prefixed parameter name
541 public function encodeParamName( $paramName ) {
542 return $this->mModulePrefix
. $paramName;
546 * Using getAllowedParams(), this function makes an array of the values
547 * provided by the user, with key being the name of the variable, and
548 * value - validated value from user or default. limits will not be
549 * parsed if $parseLimit is set to false; use this when the max
550 * limit is not definitive yet, e.g. when getting revisions.
551 * @param bool $parseLimit True by default
554 public function extractRequestParams( $parseLimit = true ) {
555 // Cache parameters, for performance and to avoid bug 24564.
556 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
557 $params = $this->getFinalParams();
560 if ( $params ) { // getFinalParams() can return false
561 foreach ( $params as $paramName => $paramSettings ) {
562 $results[$paramName] = $this->getParameterFromSettings(
563 $paramName, $paramSettings, $parseLimit );
566 $this->mParamCache
[$parseLimit] = $results;
569 return $this->mParamCache
[$parseLimit];
573 * Get a value for the given parameter
574 * @param string $paramName Parameter name
575 * @param bool $parseLimit See extractRequestParams()
576 * @return mixed Parameter value
578 protected function getParameter( $paramName, $parseLimit = true ) {
579 $params = $this->getFinalParams();
580 $paramSettings = $params[$paramName];
582 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
586 * Die if none or more than one of a certain set of parameters is set and not false.
588 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
589 * @param string $required,... Names of parameters of which exactly one must be set
591 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
592 $required = func_get_args();
593 array_shift( $required );
594 $p = $this->getModulePrefix();
596 $intersection = array_intersect( array_keys( array_filter( $params,
597 array( $this, "parameterNotEmpty" ) ) ), $required );
599 if ( count( $intersection ) > 1 ) {
601 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
603 } elseif ( count( $intersection ) == 0 ) {
605 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
612 * Die if more than one of a certain set of parameters is set and not false.
614 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
615 * @param string $required,... Names of parameters of which at most one must be set
617 public function requireMaxOneParameter( $params, $required /*...*/ ) {
618 $required = func_get_args();
619 array_shift( $required );
620 $p = $this->getModulePrefix();
622 $intersection = array_intersect( array_keys( array_filter( $params,
623 array( $this, "parameterNotEmpty" ) ) ), $required );
625 if ( count( $intersection ) > 1 ) {
627 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
634 * Die if none of a certain set of parameters is set and not false.
637 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
638 * @param string $required,... Names of parameters of which at least one must be set
640 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
641 $required = func_get_args();
642 array_shift( $required );
643 $p = $this->getModulePrefix();
645 $intersection = array_intersect(
646 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
650 if ( count( $intersection ) == 0 ) {
651 $this->dieUsage( "At least one of the parameters {$p}" .
652 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
657 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
659 * @param object $x Parameter to check is not null/false
662 private function parameterNotEmpty( $x ) {
663 return !is_null( $x ) && $x !== false;
667 * Get a WikiPage object from a title or pageid param, if possible.
668 * Can die, if no param is set or if the title or page id is not valid.
670 * @param array $params
671 * @param bool|string $load Whether load the object's state from the database:
672 * - false: don't load (if the pageid is given, it will still be loaded)
673 * - 'fromdb': load from a slave database
674 * - 'fromdbmaster': load from the master database
677 public function getTitleOrPageId( $params, $load = false ) {
678 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
681 if ( isset( $params['title'] ) ) {
682 $titleObj = Title
::newFromText( $params['title'] );
683 if ( !$titleObj ||
$titleObj->isExternal() ) {
684 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
686 if ( !$titleObj->canExist() ) {
687 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
689 $pageObj = WikiPage
::factory( $titleObj );
690 if ( $load !== false ) {
691 $pageObj->loadPageData( $load );
693 } elseif ( isset( $params['pageid'] ) ) {
694 if ( $load === false ) {
697 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
699 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
707 * Return true if we're to watch the page, false if not, null if no change.
708 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
709 * @param Title $titleObj The page under consideration
710 * @param string $userOption The user option to consider when $watchlist=preferences.
711 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
714 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
716 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
718 switch ( $watchlist ) {
726 # If the user is already watching, don't bother checking
727 if ( $userWatching ) {
730 # If no user option was passed, use watchdefault and watchcreations
731 if ( is_null( $userOption ) ) {
732 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
733 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
736 # Watch the article based on the user preference
737 return $this->getUser()->getBoolOption( $userOption );
740 return $userWatching;
743 return $userWatching;
748 * Using the settings determine the value for the given parameter
750 * @param string $paramName Parameter name
751 * @param array|mixed $paramSettings Default value or an array of settings
752 * using PARAM_* constants.
753 * @param bool $parseLimit Parse limit?
754 * @return mixed Parameter value
756 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
757 // Some classes may decide to change parameter names
758 $encParamName = $this->encodeParamName( $paramName );
760 if ( !is_array( $paramSettings ) ) {
761 $default = $paramSettings;
763 $type = gettype( $paramSettings );
768 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
769 ?
$paramSettings[self
::PARAM_DFLT
]
771 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
772 ?
$paramSettings[self
::PARAM_ISMULTI
]
774 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
775 ?
$paramSettings[self
::PARAM_TYPE
]
777 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
778 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
780 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
781 ?
$paramSettings[self
::PARAM_DEPRECATED
]
783 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
784 ?
$paramSettings[self
::PARAM_REQUIRED
]
787 // When type is not given, and no choices, the type is the same as $default
788 if ( !isset( $type ) ) {
789 if ( isset( $default ) ) {
790 $type = gettype( $default );
792 $type = 'NULL'; // allow everything
797 if ( $type == 'boolean' ) {
798 if ( isset( $default ) && $default !== false ) {
799 // Having a default value of anything other than 'false' is not allowed
802 "Boolean param $encParamName's default is set to '$default'. " .
803 "Boolean parameters must default to false."
807 $value = $this->getMain()->getCheck( $encParamName );
808 } elseif ( $type == 'upload' ) {
809 if ( isset( $default ) ) {
810 // Having a default value is not allowed
813 "File upload param $encParamName's default is set to " .
814 "'$default'. File upload parameters may not have a default." );
817 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
819 $value = $this->getMain()->getUpload( $encParamName );
820 if ( !$value->exists() ) {
821 // This will get the value without trying to normalize it
822 // (because trying to normalize a large binary file
823 // accidentally uploaded as a field fails spectacularly)
824 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
825 if ( $value !== null ) {
827 "File upload param $encParamName is not a file upload; " .
828 "be sure to use multipart/form-data for your POST and include " .
829 "a filename in the Content-Disposition header.",
830 "badupload_{$encParamName}"
835 $value = $this->getMain()->getVal( $encParamName, $default );
837 if ( isset( $value ) && $type == 'namespace' ) {
838 $type = MWNamespace
::getValidNamespaces();
840 if ( isset( $value ) && $type == 'submodule' ) {
841 $type = $this->getModuleManager()->getNames( $paramName );
845 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
846 $value = $this->parseMultiValue(
850 is_array( $type ) ?
$type : null
854 // More validation only when choices were not given
855 // choices were validated in parseMultiValue()
856 if ( isset( $value ) ) {
857 if ( !is_array( $type ) ) {
859 case 'NULL': // nothing to do
862 if ( $required && $value === '' ) {
863 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
866 case 'integer': // Force everything using intval() and optionally validate limits
867 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
868 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
869 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
870 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
872 if ( is_array( $value ) ) {
873 $value = array_map( 'intval', $value );
874 if ( !is_null( $min ) ||
!is_null( $max ) ) {
875 foreach ( $value as &$v ) {
876 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
880 $value = intval( $value );
881 if ( !is_null( $min ) ||
!is_null( $max ) ) {
882 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
887 if ( !$parseLimit ) {
888 // Don't do any validation whatsoever
891 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
892 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
896 "MAX1 or MAX2 are not defined for the limit $encParamName"
900 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
902 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
903 if ( $value == 'max' ) {
904 $value = $this->getMain()->canApiHighLimits()
905 ?
$paramSettings[self
::PARAM_MAX2
]
906 : $paramSettings[self
::PARAM_MAX
];
907 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
909 $value = intval( $value );
910 $this->validateLimit(
914 $paramSettings[self
::PARAM_MAX
],
915 $paramSettings[self
::PARAM_MAX2
]
921 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
925 if ( is_array( $value ) ) {
926 foreach ( $value as $key => $val ) {
927 $value[$key] = $this->validateTimestamp( $val, $encParamName );
930 $value = $this->validateTimestamp( $value, $encParamName );
934 if ( is_array( $value ) ) {
935 foreach ( $value as $key => $val ) {
936 $value[$key] = $this->validateUser( $val, $encParamName );
939 $value = $this->validateUser( $value, $encParamName );
942 case 'upload': // nothing to do
945 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
949 // Throw out duplicates if requested
950 if ( !$dupes && is_array( $value ) ) {
951 $value = array_unique( $value );
954 // Set a warning if a deprecated parameter has been passed
955 if ( $deprecated && $value !== false ) {
956 $this->setWarning( "The $encParamName parameter has been deprecated." );
958 } elseif ( $required ) {
959 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
966 * Return an array of values that were given in a 'a|b|c' notation,
967 * after it optionally validates them against the list allowed values.
969 * @param string $valueName The name of the parameter (for error
971 * @param mixed $value The value being parsed
972 * @param bool $allowMultiple Can $value contain more than one value
974 * @param string[]|null $allowedValues An array of values to check against. If
975 * null, all values are accepted.
976 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
978 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
979 if ( trim( $value ) === '' && $allowMultiple ) {
983 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
984 // because it unstubs $wgUser
985 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
986 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
990 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
991 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
992 "the limit is $sizeLimit" );
995 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
996 // Bug 33482 - Allow entries with | in them for non-multiple values
997 if ( in_array( $value, $allowedValues, true ) ) {
1001 $possibleValues = is_array( $allowedValues )
1002 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1005 "Only one $possibleValues is allowed for parameter '$valueName'",
1006 "multival_$valueName"
1010 if ( is_array( $allowedValues ) ) {
1011 // Check for unknown values
1012 $unknown = array_diff( $valuesList, $allowedValues );
1013 if ( count( $unknown ) ) {
1014 if ( $allowMultiple ) {
1015 $s = count( $unknown ) > 1 ?
's' : '';
1016 $vals = implode( ", ", $unknown );
1017 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1020 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1021 "unknown_$valueName"
1025 // Now throw them out
1026 $valuesList = array_intersect( $valuesList, $allowedValues );
1029 return $allowMultiple ?
$valuesList : $valuesList[0];
1033 * Validate the value against the minimum and user/bot maximum limits.
1034 * Prints usage info on failure.
1035 * @param string $paramName Parameter name
1036 * @param int $value Parameter value
1037 * @param int|null $min Minimum value
1038 * @param int|null $max Maximum value for users
1039 * @param int $botMax Maximum value for sysops/bots
1040 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1042 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1043 if ( !is_null( $min ) && $value < $min ) {
1045 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1046 $this->warnOrDie( $msg, $enforceLimits );
1050 // Minimum is always validated, whereas maximum is checked only if not
1051 // running in internal call mode
1052 if ( $this->getMain()->isInternalMode() ) {
1056 // Optimization: do not check user's bot status unless really needed -- skips db query
1057 // assumes $botMax >= $max
1058 if ( !is_null( $max ) && $value > $max ) {
1059 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1060 if ( $value > $botMax ) {
1061 $msg = $this->encodeParamName( $paramName ) .
1062 " may not be over $botMax (set to $value) for bots or sysops";
1063 $this->warnOrDie( $msg, $enforceLimits );
1067 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1068 $this->warnOrDie( $msg, $enforceLimits );
1075 * Validate and normalize of parameters of type 'timestamp'
1076 * @param string $value Parameter value
1077 * @param string $encParamName Parameter name
1078 * @return string Validated and normalized parameter
1080 protected function validateTimestamp( $value, $encParamName ) {
1081 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1082 if ( $unixTimestamp === false ) {
1084 "Invalid value '$value' for timestamp parameter $encParamName",
1085 "badtimestamp_{$encParamName}"
1089 return wfTimestamp( TS_MW
, $unixTimestamp );
1093 * Validate the supplied token.
1096 * @param string $token Supplied token
1097 * @param array $params All supplied parameters for the module
1099 * @throws MWException
1101 final public function validateToken( $token, array $params ) {
1102 $tokenType = $this->needsToken();
1103 $salts = ApiQueryTokens
::getTokenTypeSalts();
1104 if ( !isset( $salts[$tokenType] ) ) {
1105 throw new MWException(
1106 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1107 'without registering it'
1111 if ( $this->getUser()->matchEditToken(
1119 $webUiSalt = $this->getWebUITokenSalt( $params );
1120 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1132 * Validate and normalize of parameters of type 'user'
1133 * @param string $value Parameter value
1134 * @param string $encParamName Parameter name
1135 * @return string Validated and normalized parameter
1137 private function validateUser( $value, $encParamName ) {
1138 $title = Title
::makeTitleSafe( NS_USER
, $value );
1139 if ( $title === null ) {
1141 "Invalid value '$value' for user parameter $encParamName",
1142 "baduser_{$encParamName}"
1146 return $title->getText();
1151 /************************************************************************//**
1152 * @name Utility methods
1157 * Set a watch (or unwatch) based the based on a watchlist parameter.
1158 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1159 * @param Title $titleObj The article's title to change
1160 * @param string $userOption The user option to consider when $watch=preferences
1162 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1163 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1164 if ( $value === null ) {
1168 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1172 * Truncate an array to a certain length.
1173 * @param array $arr Array to truncate
1174 * @param int $limit Maximum length
1175 * @return bool True if the array was truncated, false otherwise
1177 public static function truncateArray( &$arr, $limit ) {
1179 while ( count( $arr ) > $limit ) {
1188 * Gets the user for whom to get the watchlist
1190 * @param array $params
1193 public function getWatchlistUser( $params ) {
1194 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1195 $user = User
::newFromName( $params['owner'], false );
1196 if ( !( $user && $user->getId() ) ) {
1197 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1199 $token = $user->getOption( 'watchlisttoken' );
1200 if ( $token == '' ||
$token != $params['token'] ) {
1202 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1207 if ( !$this->getUser()->isLoggedIn() ) {
1208 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1210 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1211 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1213 $user = $this->getUser();
1220 * A subset of wfEscapeWikiText for BC texts
1223 * @param string|array $v
1224 * @return string|array
1226 private static function escapeWikiText( $v ) {
1227 if ( is_array( $v ) ) {
1228 return array_map( 'self::escapeWikiText', $v );
1230 return strtr( $v, array(
1231 '__' => '__', '{' => '{', '}' => '}',
1232 '[[Category:' => '[[:Category:',
1233 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1239 * Create a Message from a string or array
1241 * A string is used as a message key. An array has the message key as the
1242 * first value and message parameters as subsequent values.
1245 * @param string|array|Message $msg
1246 * @param IContextSource $context
1247 * @param array $params
1248 * @return Message|null
1250 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1251 if ( is_string( $msg ) ) {
1252 $msg = wfMessage( $msg );
1253 } elseif ( is_array( $msg ) ) {
1254 $msg = call_user_func_array( 'wfMessage', $msg );
1256 if ( !$msg instanceof Message
) {
1260 $msg->setContext( $context );
1262 $msg->params( $params );
1270 /************************************************************************//**
1271 * @name Warning and error reporting
1276 * Set warning section for this module. Users should monitor this
1277 * section to notice any changes in API. Multiple calls to this
1278 * function will result in the warning messages being separated by
1280 * @param string $warning Warning message
1282 public function setWarning( $warning ) {
1283 $msg = new ApiRawMessage( $warning, 'warning' );
1284 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1288 * Adds a warning to the output, else dies
1290 * @param string $msg Message to show as a warning, or error message if dying
1291 * @param bool $enforceLimits Whether this is an enforce (die)
1293 private function warnOrDie( $msg, $enforceLimits = false ) {
1294 if ( $enforceLimits ) {
1295 $this->dieUsage( $msg, 'integeroutofrange' );
1298 $this->setWarning( $msg );
1302 * Throw a UsageException, which will (if uncaught) call the main module's
1303 * error handler and die with an error message.
1305 * @param string $description One-line human-readable description of the
1306 * error condition, e.g., "The API requires a valid action parameter"
1307 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1308 * automated identification of the error, e.g., 'unknown_action'
1309 * @param int $httpRespCode HTTP response code
1310 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1311 * @throws UsageException
1313 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1314 throw new UsageException(
1316 $this->encodeParamName( $errorCode ),
1323 * Get error (as code, string) from a Status object.
1326 * @param Status $status
1327 * @return array Array of code and error string
1328 * @throws MWException
1330 public function getErrorFromStatus( $status ) {
1331 if ( $status->isGood() ) {
1332 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1335 $errors = $status->getErrorsArray();
1337 // No errors? Assume the warnings should be treated as errors
1338 $errors = $status->getWarningsArray();
1341 // Still no errors? Punt
1342 $errors = array( array( 'unknownerror-nocode' ) );
1345 // Cannot use dieUsageMsg() because extensions might return custom
1347 if ( $errors[0] instanceof Message
) {
1349 $code = $msg->getKey();
1351 $code = array_shift( $errors[0] );
1352 $msg = wfMessage( $code, $errors[0] );
1354 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1355 // Translate message to code, for backwards compatibility
1356 $code = ApiBase
::$messageMap[$code]['code'];
1359 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1363 * Throw a UsageException based on the errors in the Status object.
1366 * @param Status $status
1367 * @throws MWException
1369 public function dieStatus( $status ) {
1371 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1372 $this->dieUsage( $msg, $code );
1375 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1377 * Array that maps message keys to error messages. $1 and friends are replaced.
1379 public static $messageMap = array(
1380 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1381 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1382 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1384 // Messages from Title::getUserPermissionsErrors()
1385 'ns-specialprotected' => array(
1386 'code' => 'unsupportednamespace',
1387 'info' => "Pages in the Special namespace can't be edited"
1389 'protectedinterface' => array(
1390 'code' => 'protectednamespace-interface',
1391 'info' => "You're not allowed to edit interface messages"
1393 'namespaceprotected' => array(
1394 'code' => 'protectednamespace',
1395 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1397 'customcssprotected' => array(
1398 'code' => 'customcssprotected',
1399 'info' => "You're not allowed to edit custom CSS pages"
1401 'customjsprotected' => array(
1402 'code' => 'customjsprotected',
1403 'info' => "You're not allowed to edit custom JavaScript pages"
1405 'cascadeprotected' => array(
1406 'code' => 'cascadeprotected',
1407 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1409 'protectedpagetext' => array(
1410 'code' => 'protectedpage',
1411 'info' => "The \"\$1\" right is required to edit this page"
1413 'protect-cantedit' => array(
1414 'code' => 'cantedit',
1415 'info' => "You can't protect this page because you can't edit it"
1417 'deleteprotected' => array(
1418 'code' => 'cantedit',
1419 'info' => "You can't delete this page because it has been protected"
1421 'badaccess-group0' => array(
1422 'code' => 'permissiondenied',
1423 'info' => "Permission denied"
1424 ), // Generic permission denied message
1425 'badaccess-groups' => array(
1426 'code' => 'permissiondenied',
1427 'info' => "Permission denied"
1429 'titleprotected' => array(
1430 'code' => 'protectedtitle',
1431 'info' => "This title has been protected from creation"
1433 'nocreate-loggedin' => array(
1434 'code' => 'cantcreate',
1435 'info' => "You don't have permission to create new pages"
1437 'nocreatetext' => array(
1438 'code' => 'cantcreate-anon',
1439 'info' => "Anonymous users can't create new pages"
1441 'movenologintext' => array(
1442 'code' => 'cantmove-anon',
1443 'info' => "Anonymous users can't move pages"
1445 'movenotallowed' => array(
1446 'code' => 'cantmove',
1447 'info' => "You don't have permission to move pages"
1449 'confirmedittext' => array(
1450 'code' => 'confirmemail',
1451 'info' => "You must confirm your email address before you can edit"
1453 'blockedtext' => array(
1454 'code' => 'blocked',
1455 'info' => "You have been blocked from editing"
1457 'autoblockedtext' => array(
1458 'code' => 'autoblocked',
1459 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1462 // Miscellaneous interface messages
1463 'actionthrottledtext' => array(
1464 'code' => 'ratelimited',
1465 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1467 'alreadyrolled' => array(
1468 'code' => 'alreadyrolled',
1469 'info' => "The page you tried to rollback was already rolled back"
1471 'cantrollback' => array(
1472 'code' => 'onlyauthor',
1473 'info' => "The page you tried to rollback only has one author"
1475 'readonlytext' => array(
1476 'code' => 'readonly',
1477 'info' => "The wiki is currently in read-only mode"
1479 'sessionfailure' => array(
1480 'code' => 'badtoken',
1481 'info' => "Invalid token" ),
1482 'cannotdelete' => array(
1483 'code' => 'cantdelete',
1484 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1486 'notanarticle' => array(
1487 'code' => 'missingtitle',
1488 'info' => "The page you requested doesn't exist"
1490 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1492 'immobile_namespace' => array(
1493 'code' => 'immobilenamespace',
1494 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1496 'articleexists' => array(
1497 'code' => 'articleexists',
1498 'info' => "The destination article already exists and is not a redirect to the source article"
1500 'protectedpage' => array(
1501 'code' => 'protectedpage',
1502 'info' => "You don't have permission to perform this move"
1504 'hookaborted' => array(
1505 'code' => 'hookaborted',
1506 'info' => "The modification you tried to make was aborted by an extension hook"
1508 'cantmove-titleprotected' => array(
1509 'code' => 'protectedtitle',
1510 'info' => "The destination article has been protected from creation"
1512 'imagenocrossnamespace' => array(
1513 'code' => 'nonfilenamespace',
1514 'info' => "Can't move a file to a non-file namespace"
1516 'imagetypemismatch' => array(
1517 'code' => 'filetypemismatch',
1518 'info' => "The new file extension doesn't match its type"
1520 // 'badarticleerror' => shouldn't happen
1521 // 'badtitletext' => shouldn't happen
1522 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1523 'range_block_disabled' => array(
1524 'code' => 'rangedisabled',
1525 'info' => "Blocking IP ranges has been disabled"
1527 'nosuchusershort' => array(
1528 'code' => 'nosuchuser',
1529 'info' => "The user you specified doesn't exist"
1531 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1532 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1533 'ipb_already_blocked' => array(
1534 'code' => 'alreadyblocked',
1535 'info' => "The user you tried to block was already blocked"
1537 'ipb_blocked_as_range' => array(
1538 'code' => 'blockedasrange',
1539 '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."
1541 'ipb_cant_unblock' => array(
1542 'code' => 'cantunblock',
1543 'info' => "The block you specified was not found. It may have been unblocked already"
1545 'mailnologin' => array(
1546 'code' => 'cantsend',
1547 '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"
1549 'ipbblocked' => array(
1550 'code' => 'ipbblocked',
1551 'info' => 'You cannot block or unblock users while you are yourself blocked'
1553 'ipbnounblockself' => array(
1554 'code' => 'ipbnounblockself',
1555 'info' => 'You are not allowed to unblock yourself'
1557 'usermaildisabled' => array(
1558 'code' => 'usermaildisabled',
1559 'info' => "User email has been disabled"
1561 'blockedemailuser' => array(
1562 'code' => 'blockedfrommail',
1563 'info' => "You have been blocked from sending email"
1565 'notarget' => array(
1566 'code' => 'notarget',
1567 'info' => "You have not specified a valid target for this action"
1570 'code' => 'noemail',
1571 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1573 'rcpatroldisabled' => array(
1574 'code' => 'patroldisabled',
1575 'info' => "Patrolling is disabled on this wiki"
1577 'markedaspatrollederror-noautopatrol' => array(
1578 'code' => 'noautopatrol',
1579 'info' => "You don't have permission to patrol your own changes"
1581 'delete-toobig' => array(
1582 'code' => 'bigdelete',
1583 'info' => "You can't delete this page because it has more than \$1 revisions"
1585 'movenotallowedfile' => array(
1586 'code' => 'cantmovefile',
1587 'info' => "You don't have permission to move files"
1589 'userrights-no-interwiki' => array(
1590 'code' => 'nointerwikiuserrights',
1591 'info' => "You don't have permission to change user rights on other wikis"
1593 'userrights-nodatabase' => array(
1594 'code' => 'nosuchdatabase',
1595 'info' => "Database \"\$1\" does not exist or is not local"
1597 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1598 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1599 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1600 'import-rootpage-invalid' => array(
1601 'code' => 'import-rootpage-invalid',
1602 'info' => 'Root page is an invalid title'
1604 'import-rootpage-nosubpage' => array(
1605 'code' => 'import-rootpage-nosubpage',
1606 'info' => 'Namespace "$1" of the root page does not allow subpages'
1609 // API-specific messages
1610 'readrequired' => array(
1611 'code' => 'readapidenied',
1612 'info' => "You need read permission to use this module"
1614 'writedisabled' => array(
1615 'code' => 'noapiwrite',
1616 '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"
1618 'writerequired' => array(
1619 'code' => 'writeapidenied',
1620 'info' => "You're not allowed to edit this wiki through the API"
1622 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1623 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1624 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1625 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1626 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1627 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1628 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1629 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1630 'create-titleexists' => array(
1631 'code' => 'create-titleexists',
1632 'info' => "Existing titles can't be protected with 'create'"
1634 'missingtitle-createonly' => array(
1635 'code' => 'missingtitle-createonly',
1636 'info' => "Missing titles can only be protected with 'create'"
1638 'cantblock' => array( 'code' => 'cantblock',
1639 'info' => "You don't have permission to block users"
1641 'canthide' => array(
1642 'code' => 'canthide',
1643 'info' => "You don't have permission to hide user names from the block log"
1645 'cantblock-email' => array(
1646 'code' => 'cantblock-email',
1647 'info' => "You don't have permission to block users from sending email through the wiki"
1649 'unblock-notarget' => array(
1650 'code' => 'notarget',
1651 'info' => "Either the id or the user parameter must be set"
1653 'unblock-idanduser' => array(
1654 'code' => 'idanduser',
1655 'info' => "The id and user parameters can't be used together"
1657 'cantunblock' => array(
1658 'code' => 'permissiondenied',
1659 'info' => "You don't have permission to unblock users"
1661 'cannotundelete' => array(
1662 'code' => 'cantundelete',
1663 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1665 'permdenied-undelete' => array(
1666 'code' => 'permissiondenied',
1667 'info' => "You don't have permission to restore deleted revisions"
1669 'createonly-exists' => array(
1670 'code' => 'articleexists',
1671 'info' => "The article you tried to create has been created already"
1673 'nocreate-missing' => array(
1674 'code' => 'missingtitle',
1675 'info' => "The article you tried to edit doesn't exist"
1677 'cantchangecontentmodel' => array(
1678 'code' => 'cantchangecontentmodel',
1679 'info' => "You don't have permission to change the content model of a page"
1681 'nosuchrcid' => array(
1682 'code' => 'nosuchrcid',
1683 'info' => "There is no change with rcid \"\$1\""
1685 'nosuchlogid' => array(
1686 'code' => 'nosuchlogid',
1687 'info' => "There is no log entry with ID \"\$1\""
1689 'protect-invalidaction' => array(
1690 'code' => 'protect-invalidaction',
1691 'info' => "Invalid protection type \"\$1\""
1693 'protect-invalidlevel' => array(
1694 'code' => 'protect-invalidlevel',
1695 'info' => "Invalid protection level \"\$1\""
1697 'toofewexpiries' => array(
1698 'code' => 'toofewexpiries',
1699 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1701 'cantimport' => array(
1702 'code' => 'cantimport',
1703 'info' => "You don't have permission to import pages"
1705 'cantimport-upload' => array(
1706 'code' => 'cantimport-upload',
1707 'info' => "You don't have permission to import uploaded pages"
1709 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1710 'importuploaderrorsize' => array(
1711 'code' => 'filetoobig',
1712 'info' => 'The file you uploaded is bigger than the maximum upload size'
1714 'importuploaderrorpartial' => array(
1715 'code' => 'partialupload',
1716 'info' => 'The file was only partially uploaded'
1718 'importuploaderrortemp' => array(
1719 'code' => 'notempdir',
1720 'info' => 'The temporary upload directory is missing'
1722 'importcantopen' => array(
1723 'code' => 'cantopenfile',
1724 'info' => "Couldn't open the uploaded file"
1726 'import-noarticle' => array(
1727 'code' => 'badinterwiki',
1728 'info' => 'Invalid interwiki title specified'
1730 'importbadinterwiki' => array(
1731 'code' => 'badinterwiki',
1732 'info' => 'Invalid interwiki title specified'
1734 'import-unknownerror' => array(
1735 'code' => 'import-unknownerror',
1736 'info' => "Unknown error on import: \"\$1\""
1738 'cantoverwrite-sharedfile' => array(
1739 'code' => 'cantoverwrite-sharedfile',
1740 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1742 'sharedfile-exists' => array(
1743 'code' => 'fileexists-sharedrepo-perm',
1744 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1746 'mustbeposted' => array(
1747 'code' => 'mustbeposted',
1748 'info' => "The \$1 module requires a POST request"
1752 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1754 'specialpage-cantexecute' => array(
1755 'code' => 'specialpage-cantexecute',
1756 'info' => "You don't have permission to view the results of this special page"
1758 'invalidoldimage' => array(
1759 'code' => 'invalidoldimage',
1760 'info' => 'The oldimage parameter has invalid format'
1762 'nodeleteablefile' => array(
1763 'code' => 'nodeleteablefile',
1764 'info' => 'No such old version of the file'
1766 'fileexists-forbidden' => array(
1767 'code' => 'fileexists-forbidden',
1768 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1770 'fileexists-shared-forbidden' => array(
1771 'code' => 'fileexists-shared-forbidden',
1772 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1774 'filerevert-badversion' => array(
1775 'code' => 'filerevert-badversion',
1776 'info' => 'There is no previous local version of this file with the provided timestamp.'
1779 // ApiEditPage messages
1780 'noimageredirect-anon' => array(
1781 'code' => 'noimageredirect-anon',
1782 'info' => "Anonymous users can't create image redirects"
1784 'noimageredirect-logged' => array(
1785 'code' => 'noimageredirect',
1786 'info' => "You don't have permission to create image redirects"
1788 'spamdetected' => array(
1789 'code' => 'spamdetected',
1790 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1792 'contenttoobig' => array(
1793 'code' => 'contenttoobig',
1794 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1796 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1797 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1798 'wasdeleted' => array(
1799 'code' => 'pagedeleted',
1800 'info' => "The page has been deleted since you fetched its timestamp"
1802 'blankpage' => array(
1803 'code' => 'emptypage',
1804 'info' => "Creating new, empty pages is not allowed"
1806 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1807 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1808 'missingtext' => array(
1810 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1812 'emptynewsection' => array(
1813 'code' => 'emptynewsection',
1814 'info' => 'Creating empty new sections is not possible.'
1816 'revwrongpage' => array(
1817 'code' => 'revwrongpage',
1818 'info' => "r\$1 is not a revision of \"\$2\""
1820 'undo-failure' => array(
1821 'code' => 'undofailure',
1822 'info' => 'Undo failed due to conflicting intermediate edits'
1824 'content-not-allowed-here' => array(
1825 'code' => 'contentnotallowedhere',
1826 'info' => 'Content model "$1" is not allowed at title "$2"'
1829 // Messages from WikiPage::doEit()
1830 'edit-hook-aborted' => array(
1831 'code' => 'edit-hook-aborted',
1832 'info' => "Your edit was aborted by an ArticleSave hook"
1834 'edit-gone-missing' => array(
1835 'code' => 'edit-gone-missing',
1836 'info' => "The page you tried to edit doesn't seem to exist anymore"
1838 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1839 'edit-already-exists' => array(
1840 'code' => 'edit-already-exists',
1841 'info' => 'It seems the page you tried to create already exist'
1845 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1846 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1847 'uploaddisabled' => array(
1848 'code' => 'uploaddisabled',
1849 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1851 'copyuploaddisabled' => array(
1852 'code' => 'copyuploaddisabled',
1853 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1855 'copyuploadbaddomain' => array(
1856 'code' => 'copyuploadbaddomain',
1857 'info' => 'Uploads by URL are not allowed from this domain.'
1859 'copyuploadbadurl' => array(
1860 'code' => 'copyuploadbadurl',
1861 'info' => 'Upload not allowed from this URL.'
1864 'filename-tooshort' => array(
1865 'code' => 'filename-tooshort',
1866 'info' => 'The filename is too short'
1868 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1869 'illegal-filename' => array(
1870 'code' => 'illegal-filename',
1871 'info' => 'The filename is not allowed'
1873 'filetype-missing' => array(
1874 'code' => 'filetype-missing',
1875 'info' => 'The file is missing an extension'
1878 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1880 // @codingStandardsIgnoreEnd
1883 * Helper function for readonly errors
1885 public function dieReadOnly() {
1886 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1887 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1888 array( 'readonlyreason' => wfReadOnlyReason() ) );
1892 * Output the error message related to a certain array
1893 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1895 public function dieUsageMsg( $error ) {
1896 # most of the time we send a 1 element, so we might as well send it as
1897 # a string and make this an array here.
1898 if ( is_string( $error ) ) {
1899 $error = array( $error );
1901 $parsed = $this->parseMsg( $error );
1902 $this->dieUsage( $parsed['info'], $parsed['code'] );
1906 * Will only set a warning instead of failing if the global $wgDebugAPI
1907 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1908 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1911 public function dieUsageMsgOrDebug( $error ) {
1912 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1913 $this->dieUsageMsg( $error );
1916 if ( is_string( $error ) ) {
1917 $error = array( $error );
1919 $parsed = $this->parseMsg( $error );
1920 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1924 * Die with the $prefix.'badcontinue' error. This call is common enough to
1925 * make it into the base method.
1926 * @param bool $condition Will only die if this value is true
1929 protected function dieContinueUsageIf( $condition ) {
1932 'Invalid continue param. You should pass the original value returned by the previous query',
1938 * Return the error message related to a certain array
1939 * @param array $error Element of a getUserPermissionsErrors()-style array
1940 * @return array('code' => code, 'info' => info)
1942 public function parseMsg( $error ) {
1943 $error = (array)$error; // It seems strings sometimes make their way in here
1944 $key = array_shift( $error );
1946 // Check whether the error array was nested
1947 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1948 if ( is_array( $key ) ) {
1950 $key = array_shift( $error );
1953 if ( isset( self
::$messageMap[$key] ) ) {
1955 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1956 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1960 // If the key isn't present, throw an "unknown error"
1961 return $this->parseMsg( array( 'unknownerror', $key ) );
1965 * Internal code errors should be reported with this method
1966 * @param string $method Method or function name
1967 * @param string $message Error message
1968 * @throws MWException
1970 protected static function dieDebug( $method, $message ) {
1971 throw new MWException( "Internal error in $method: $message" );
1975 * Write logging information for API features to a debug log, for usage
1977 * @param string $feature Feature being used.
1979 protected function logFeatureUsage( $feature ) {
1980 $request = $this->getRequest();
1981 $s = '"' . addslashes( $feature ) . '"' .
1982 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1983 ' "' . $request->getIP() . '"' .
1984 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1985 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1986 wfDebugLog( 'api-feature-usage', $s, 'private' );
1991 /************************************************************************//**
1992 * @name Help message generation
1997 * Return the description message.
1999 * @return string|array|Message
2001 protected function getDescriptionMessage() {
2002 return "apihelp-{$this->getModulePath()}-description";
2006 * Get final module description, after hooks have had a chance to tweak it as
2009 * @since 1.25, returns Message[] rather than string[]
2012 public function getFinalDescription() {
2013 $desc = $this->getDescription();
2014 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2015 $desc = self
::escapeWikiText( $desc );
2016 if ( is_array( $desc ) ) {
2017 $desc = join( "\n", $desc );
2019 $desc = (string)$desc;
2022 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2023 $this->getModulePrefix(),
2024 $this->getModuleName(),
2025 $this->getModulePath(),
2027 if ( !$msg->exists() ) {
2028 $msg = $this->msg( 'api-help-fallback-description', $desc );
2030 $msgs = array( $msg );
2032 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2038 * Get final list of parameters, after hooks have had a chance to
2039 * tweak it as needed.
2041 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2042 * @return array|bool False on no parameters
2043 * @since 1.21 $flags param added
2045 public function getFinalParams( $flags = 0 ) {
2046 $params = $this->getAllowedParams( $flags );
2051 if ( $this->needsToken() ) {
2052 $params['token'] = array(
2053 ApiBase
::PARAM_TYPE
=> 'string',
2054 ApiBase
::PARAM_REQUIRED
=> true,
2055 ApiBase
::PARAM_HELP_MSG
=> array(
2056 'api-help-param-token',
2057 $this->needsToken(),
2059 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2062 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2068 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2071 * @since 1.25, returns array of Message[] rather than array of string[]
2072 * @return array Keys are parameter names, values are arrays of Message objects
2074 public function getFinalParamDescription() {
2075 $prefix = $this->getModulePrefix();
2076 $name = $this->getModuleName();
2077 $path = $this->getModulePath();
2079 $desc = $this->getParamDescription();
2080 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2085 $desc = self
::escapeWikiText( $desc );
2087 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2089 foreach ( $params as $param => $settings ) {
2090 if ( !is_array( $settings ) ) {
2091 $settings = array();
2094 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2095 if ( is_array( $d ) ) {
2096 // Special handling for prop parameters
2097 $d = array_map( function ( $line ) {
2098 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2099 $line = "\n;{$m[1]}:{$m[2]}";
2103 $d = join( ' ', $d );
2106 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2107 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2109 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2110 if ( !$msg->exists() ) {
2111 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2114 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2115 array( $prefix, $param, $name, $path ) );
2117 $this->dieDebug( __METHOD__
,
2118 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2120 $msgs[$param] = array( $msg );
2122 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2123 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2124 $this->dieDebug( __METHOD__
,
2125 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2127 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2128 $this->dieDebug( __METHOD__
,
2129 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2130 'ApiBase::PARAM_TYPE is an array' );
2133 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2134 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2135 if ( isset( $valueMsgs[$value] ) ) {
2136 $msg = $valueMsgs[$value];
2138 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2140 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2141 array( $prefix, $param, $name, $path, $value ) );
2143 $m = new ApiHelpParamValueMessage(
2145 array( $m->getKey(), 'api-help-param-no-description' ),
2148 $msgs[$param][] = $m->setContext( $this->getContext() );
2150 $this->dieDebug( __METHOD__
,
2151 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2156 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2157 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2158 $this->dieDebug( __METHOD__
,
2159 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2161 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2162 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2163 array( $prefix, $param, $name, $path ) );
2165 $msgs[$param][] = $m;
2167 $this->dieDebug( __METHOD__
,
2168 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2174 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2180 * Generates the list of flags for the help screen and for action=paraminfo
2182 * Corresponding messages: api-help-flag-deprecated,
2183 * api-help-flag-internal, api-help-flag-readrights,
2184 * api-help-flag-writerights, api-help-flag-mustbeposted
2188 protected function getHelpFlags() {
2191 if ( $this->isDeprecated() ) {
2192 $flags[] = 'deprecated';
2194 if ( $this->isInternal() ) {
2195 $flags[] = 'internal';
2197 if ( $this->isReadMode() ) {
2198 $flags[] = 'readrights';
2200 if ( $this->isWriteMode() ) {
2201 $flags[] = 'writerights';
2203 if ( $this->mustBePosted() ) {
2204 $flags[] = 'mustbeposted';
2211 * Returns information about the source of this module, if known
2213 * Returned array is an array with the following keys:
2214 * - path: Install path
2215 * - name: Extension name, or "MediaWiki" for core
2216 * - namemsg: (optional) i18n message key for a display name
2217 * - license-name: (optional) Name of license
2219 * @return array|null
2221 protected function getModuleSourceInfo() {
2224 if ( $this->mModuleSource
!== false ) {
2225 return $this->mModuleSource
;
2228 // First, try to find where the module comes from...
2229 $rClass = new ReflectionClass( $this );
2230 $path = $rClass->getFileName();
2233 $this->mModuleSource
= null;
2236 $path = realpath( $path ) ?
: $path;
2238 // Build map of extension directories to extension info
2239 if ( self
::$extensionInfo === null ) {
2240 self
::$extensionInfo = array(
2241 realpath( __DIR__
) ?
: __DIR__
=> array(
2243 'name' => 'MediaWiki',
2244 'license-name' => 'GPL-2.0+',
2246 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2252 'license-name' => null,
2254 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2255 foreach ( $group as $ext ) {
2256 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2257 // This shouldn't happen, but does anyway.
2261 $extpath = $ext['path'];
2262 if ( !is_dir( $extpath ) ) {
2263 $extpath = dirname( $extpath );
2265 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2266 array_intersect_key( $ext, $keep );
2269 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2270 $extpath = $ext['path'];
2271 if ( !is_dir( $extpath ) ) {
2272 $extpath = dirname( $extpath );
2274 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2275 array_intersect_key( $ext, $keep );
2279 // Now traverse parent directories until we find a match or run out of
2282 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2284 $this->mModuleSource
= self
::$extensionInfo[$path];
2285 return $this->mModuleSource
;
2289 $path = dirname( $path );
2290 } while ( $path !== $oldpath );
2292 // No idea what extension this might be.
2293 $this->mModuleSource
= null;
2298 * Called from ApiHelp before the pieces are joined together and returned.
2300 * This exists mainly for ApiMain to add the Permissions and Credits
2301 * sections. Other modules probably don't need it.
2303 * @param string[] &$help Array of help data
2304 * @param array $options Options passed to ApiHelp::getHelp
2305 * @param array &$tocData If a TOC is being generated, this array has keys
2306 * as anchors in the page and values as for Linker::generateTOC().
2308 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2313 /************************************************************************//**
2318 /// @deprecated since 1.24
2319 const PROP_ROOT
= 'ROOT';
2320 /// @deprecated since 1.24
2321 const PROP_LIST
= 'LIST';
2322 /// @deprecated since 1.24
2323 const PROP_TYPE
= 0;
2324 /// @deprecated since 1.24
2325 const PROP_NULLABLE
= 1;
2328 * Formerly returned a string that identifies the version of the extending
2329 * class. Typically included the class name, the svn revision, timestamp,
2330 * and last author. Usually done with SVN's Id keyword
2332 * @deprecated since 1.21, version string is no longer supported
2335 public function getVersion() {
2336 wfDeprecated( __METHOD__
, '1.21' );
2341 * Formerly used to fetch a list of possible properites in the result,
2342 * somehow organized with respect to the prop parameter that causes them to
2343 * be returned. The specific semantics of the return value was never
2344 * specified. Since this was never possible to be accurately updated, it
2347 * @deprecated since 1.24
2348 * @return array|bool
2350 protected function getResultProperties() {
2351 wfDeprecated( __METHOD__
, '1.24' );
2356 * @see self::getResultProperties()
2357 * @deprecated since 1.24
2358 * @return array|bool
2360 public function getFinalResultProperties() {
2361 wfDeprecated( __METHOD__
, '1.24' );
2366 * @see self::getResultProperties()
2367 * @deprecated since 1.24
2369 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2370 wfDeprecated( __METHOD__
, '1.24' );
2374 * @see self::getPossibleErrors()
2375 * @deprecated since 1.24
2378 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2379 wfDeprecated( __METHOD__
, '1.24' );
2384 * @see self::getPossibleErrors()
2385 * @deprecated since 1.24
2388 public function getRequireMaxOneParameterErrorMessages( $params ) {
2389 wfDeprecated( __METHOD__
, '1.24' );
2394 * @see self::getPossibleErrors()
2395 * @deprecated since 1.24
2398 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2399 wfDeprecated( __METHOD__
, '1.24' );
2404 * @see self::getPossibleErrors()
2405 * @deprecated since 1.24
2408 public function getTitleOrPageIdErrorMessage() {
2409 wfDeprecated( __METHOD__
, '1.24' );
2414 * This formerly attempted to return a list of all possible errors returned
2415 * by the module. However, this was impossible to maintain in many cases
2416 * since errors could come from other areas of MediaWiki and in some cases
2417 * from arbitrary extension hooks. Since a partial list claiming to be
2418 * comprehensive is unlikely to be useful, it was removed.
2420 * @deprecated since 1.24
2423 public function getPossibleErrors() {
2424 wfDeprecated( __METHOD__
, '1.24' );
2429 * @see self::getPossibleErrors()
2430 * @deprecated since 1.24
2433 public function getFinalPossibleErrors() {
2434 wfDeprecated( __METHOD__
, '1.24' );
2439 * @see self::getPossibleErrors()
2440 * @deprecated since 1.24
2443 public function parseErrors( $errors ) {
2444 wfDeprecated( __METHOD__
, '1.24' );
2449 * Returns the description string for this module
2451 * Ignored if an i18n message exists for
2452 * "apihelp-{$this->getModulePathString()}-description".
2454 * @deprecated since 1.25
2455 * @return Message|string|array
2457 protected function getDescription() {
2462 * Returns an array of parameter descriptions.
2464 * For each parameter, ignored if an i18n message exists for the parameter.
2465 * By default that message is
2466 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2467 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2468 * self::getFinalParams().
2470 * @deprecated since 1.25
2471 * @return array|bool False on no parameter descriptions
2473 protected function getParamDescription() {
2478 * Returns usage examples for this module.
2480 * Return value as an array is either:
2481 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2483 * - sequential numeric keys with even-numbered keys being display-text
2484 * and odd-numbered keys being partial urls
2485 * - partial URLs as keys with display-text (string or array-to-be-joined)
2487 * Return value as a string is the same as an array with a numeric key and
2488 * that value, and boolean false means "no examples".
2490 * @deprecated since 1.25, use getExamplesMessages() instead
2491 * @return bool|string|array
2493 protected function getExamples() {
2498 * Generates help message for this module, or false if there is no description
2499 * @deprecated since 1.25
2500 * @return string|bool
2502 public function makeHelpMsg() {
2503 wfDeprecated( __METHOD__
, '1.25' );
2504 static $lnPrfx = "\n ";
2506 $msg = $this->getFinalDescription();
2508 if ( $msg !== false ) {
2510 if ( !is_array( $msg ) ) {
2515 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2517 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2519 if ( $this->isReadMode() ) {
2520 $msg .= "\nThis module requires read rights";
2522 if ( $this->isWriteMode() ) {
2523 $msg .= "\nThis module requires write rights";
2525 if ( $this->mustBePosted() ) {
2526 $msg .= "\nThis module only accepts POST requests";
2528 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2529 $this->mustBePosted()
2535 $paramsMsg = $this->makeHelpMsgParameters();
2536 if ( $paramsMsg !== false ) {
2537 $msg .= "Parameters:\n$paramsMsg";
2540 $examples = $this->getExamples();
2542 if ( !is_array( $examples ) ) {
2547 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2548 foreach ( $examples as $k => $v ) {
2549 if ( is_numeric( $k ) ) {
2552 if ( is_array( $v ) ) {
2553 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2555 $msgExample = " $v";
2558 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2568 * @deprecated since 1.25
2569 * @param string $item
2572 private function indentExampleText( $item ) {
2577 * @deprecated since 1.25
2578 * @param string $prefix Text to split output items
2579 * @param string $title What is being output
2580 * @param string|array $input
2583 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2584 wfDeprecated( __METHOD__
, '1.25' );
2585 if ( $input === false ) {
2588 if ( !is_array( $input ) ) {
2589 $input = array( $input );
2592 if ( count( $input ) > 0 ) {
2594 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2598 $msg .= implode( $prefix, $input ) . "\n";
2607 * Generates the parameter descriptions for this module, to be displayed in the
2609 * @deprecated since 1.25
2610 * @return string|bool
2612 public function makeHelpMsgParameters() {
2613 wfDeprecated( __METHOD__
, '1.25' );
2614 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2617 $paramsDescription = $this->getFinalParamDescription();
2619 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2620 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2621 foreach ( $params as $paramName => $paramSettings ) {
2622 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2623 if ( is_array( $desc ) ) {
2624 $desc = implode( $paramPrefix, $desc );
2628 if ( !is_array( $paramSettings ) ) {
2629 $paramSettings = array(
2630 self
::PARAM_DFLT
=> $paramSettings,
2634 //handle missing type
2635 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2636 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2637 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2639 if ( is_bool( $dflt ) ) {
2640 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2641 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2642 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2643 } elseif ( is_int( $dflt ) ) {
2644 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2648 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2649 && $paramSettings[self
::PARAM_DEPRECATED
]
2651 $desc = "DEPRECATED! $desc";
2654 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2655 && $paramSettings[self
::PARAM_REQUIRED
]
2657 $desc .= $paramPrefix . "This parameter is required";
2660 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2661 ?
$paramSettings[self
::PARAM_TYPE
]
2663 if ( isset( $type ) ) {
2664 $hintPipeSeparated = true;
2665 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2666 ?
$paramSettings[self
::PARAM_ISMULTI
]
2669 $prompt = 'Values (separate with \'|\'): ';
2671 $prompt = 'One value: ';
2674 if ( $type === 'submodule' ) {
2675 $type = $this->getModuleManager()->getNames( $paramName );
2678 if ( is_array( $type ) ) {
2680 $nothingPrompt = '';
2681 foreach ( $type as $t ) {
2683 $nothingPrompt = 'Can be empty, or ';
2688 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2689 $choicesstring = implode( ', ', $choices );
2690 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2691 $hintPipeSeparated = false;
2695 // Special handling because namespaces are
2696 // type-limited, yet they are not given
2697 $desc .= $paramPrefix . $prompt;
2698 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2699 100, $descWordwrap );
2700 $hintPipeSeparated = false;
2703 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2704 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2705 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2707 $desc .= ' allowed';
2710 $s = $multi ?
's' : '';
2711 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2712 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2713 if ( $hasMin ||
$hasMax ) {
2715 $intRangeStr = "The value$s must be no less than " .
2716 "{$paramSettings[self::PARAM_MIN]}";
2717 } elseif ( !$hasMin ) {
2718 $intRangeStr = "The value$s must be no more than " .
2719 "{$paramSettings[self::PARAM_MAX]}";
2721 $intRangeStr = "The value$s must be between " .
2722 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2725 $desc .= $paramPrefix . $intRangeStr;
2729 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2735 if ( $hintPipeSeparated ) {
2736 $desc .= $paramPrefix . "Separate values with '|'";
2739 $isArray = is_array( $type );
2741 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2743 $desc .= $paramPrefix . "Maximum number of values " .
2744 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2749 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2750 if ( !is_null( $default ) && $default !== false ) {
2751 $desc .= $paramPrefix . "Default: $default";
2754 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2764 * @deprecated since 1.25, always returns empty string
2765 * @param DatabaseBase|bool $db
2768 public function getModuleProfileName( $db = false ) {
2769 wfDeprecated( __METHOD__
, '1.25' );
2774 * @deprecated since 1.25
2776 public function profileIn() {
2777 // No wfDeprecated() yet because extensions call this and might need to
2778 // keep doing so for BC.
2782 * @deprecated since 1.25
2784 public function profileOut() {
2785 // No wfDeprecated() yet because extensions call this and might need to
2786 // keep doing so for BC.
2790 * @deprecated since 1.25
2792 public function safeProfileOut() {
2793 wfDeprecated( __METHOD__
, '1.25' );
2797 * @deprecated since 1.25, always returns 0
2800 public function getProfileTime() {
2801 wfDeprecated( __METHOD__
, '1.25' );
2806 * @deprecated since 1.25
2808 public function profileDBIn() {
2809 wfDeprecated( __METHOD__
, '1.25' );
2813 * @deprecated since 1.25
2815 public function profileDBOut() {
2816 wfDeprecated( __METHOD__
, '1.25' );
2820 * @deprecated since 1.25, always returns 0
2823 public function getProfileDBTime() {
2824 wfDeprecated( __METHOD__
, '1.25' );
2829 * Get the result data array (read-only)
2830 * @deprecated since 1.25, use $this->getResult() methods instead
2833 public function getResultData() {
2834 wfDeprecated( __METHOD__
, '1.25' );
2835 return $this->getResult()->getData();
2842 * For really cool vim folding this needs to be at the end:
2843 * vim: foldmarker=@{,@} foldmethod=marker