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 // When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
90 // Default is to use all modules in $this->getModuleManager() in the group
91 // matching the parameter name.
92 const PARAM_SUBMODULE_MAP
= 15;
94 // When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix added by
95 // ApiQueryGeneratorBase (and similar if anything else ever does that).
96 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
98 const LIMIT_BIG1
= 500; // Fast query, std user limit
99 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
100 const LIMIT_SML1
= 50; // Slow query, std user limit
101 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
104 * getAllowedParams() flag: When set, the result could take longer to generate,
105 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
108 const GET_VALUES_FOR_HELP
= 1;
110 /** @var array Maps extension paths to info arrays */
111 private static $extensionInfo = null;
114 private $mMainModule;
116 private $mModuleName, $mModulePrefix;
117 private $mSlaveDB = null;
118 private $mParamCache = array();
119 /** @var array|null|bool */
120 private $mModuleSource = false;
123 * @param ApiMain $mainModule
124 * @param string $moduleName Name of this module
125 * @param string $modulePrefix Prefix to use for parameter names
127 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
128 $this->mMainModule
= $mainModule;
129 $this->mModuleName
= $moduleName;
130 $this->mModulePrefix
= $modulePrefix;
132 if ( !$this->isMain() ) {
133 $this->setContext( $mainModule->getContext() );
138 /************************************************************************//**
139 * @name Methods to implement
144 * Evaluates the parameters, performs the requested query, and sets up
145 * the result. Concrete implementations of ApiBase must override this
146 * method to provide whatever functionality their module offers.
147 * Implementations must not produce any output on their own and are not
148 * expected to handle any errors.
150 * The execute() method will be invoked directly by ApiMain immediately
151 * before the result of the module is output. Aside from the
152 * constructor, implementations should assume that no other methods
153 * will be called externally on the module before the result is
156 * The result data should be stored in the ApiResult object available
157 * through getResult().
159 abstract public function execute();
162 * Get the module manager, or null if this module has no sub-modules
164 * @return ApiModuleManager
166 public function getModuleManager() {
171 * If the module may only be used with a certain format module,
172 * it should override this method to return an instance of that formatter.
173 * A value of null means the default format will be used.
174 * @note Do not use this just because you don't want to support non-json
175 * formats. This should be used only when there is a fundamental
176 * requirement for a specific format.
177 * @return mixed Instance of a derived class of ApiFormatBase, or null
179 public function getCustomPrinter() {
184 * Returns usage examples for this module.
186 * Return value has query strings as keys, with values being either strings
187 * (message key), arrays (message key + parameter), or Message objects.
189 * Do not call this base class implementation when overriding this method.
194 protected function getExamplesMessages() {
195 // Fall back to old non-localised method
198 $examples = $this->getExamples();
200 if ( !is_array( $examples ) ) {
201 $examples = array( $examples );
202 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
203 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
204 !preg_match( '/^\s*api\.php\?/', $examples[0] )
206 // Fix up the ugly "even numbered elements are description, odd
207 // numbered elemts are the link" format (see doc for self::getExamples)
209 for ( $i = 0; $i < count( $examples ); $i +
= 2 ) {
210 $tmp[$examples[$i +
1]] = $examples[$i];
215 foreach ( $examples as $k => $v ) {
216 if ( is_numeric( $k ) ) {
221 $msg = self
::escapeWikiText( $v );
222 if ( is_array( $msg ) ) {
223 $msg = join( " ", $msg );
227 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
228 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
236 * Return links to more detailed help pages about the module.
237 * @since 1.25, returning boolean false is deprecated
238 * @return string|array
240 public function getHelpUrls() {
245 * Returns an array of allowed parameters (parameter name) => (default
246 * value) or (parameter name) => (array with PARAM_* constants as keys)
247 * Don't call this function directly: use getFinalParams() to allow
248 * hooks to modify parameters as needed.
250 * Some derived classes may choose to handle an integer $flags parameter
251 * in the overriding methods. Callers of this method can pass zero or
252 * more OR-ed flags like GET_VALUES_FOR_HELP.
256 protected function getAllowedParams( /* $flags = 0 */ ) {
257 // int $flags is not declared because it causes "Strict standards"
258 // warning. Most derived classes do not implement it.
263 * Indicates if this module needs maxlag to be checked
266 public function shouldCheckMaxlag() {
271 * Indicates whether this module requires read rights
274 public function isReadMode() {
279 * Indicates whether this module requires write mode
282 public function isWriteMode() {
287 * Indicates whether this module must be called with a POST request
290 public function mustBePosted() {
291 return $this->needsToken() !== false;
295 * Indicates whether this module is deprecated
299 public function isDeprecated() {
304 * Indicates whether this module is "internal"
305 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
309 public function isInternal() {
314 * Returns the token type this module requires in order to execute.
316 * Modules are strongly encouraged to use the core 'csrf' type unless they
317 * have specialized security needs. If the token type is not one of the
318 * core types, you must use the ApiQueryTokensRegisterTypes hook to
321 * Returning a non-falsey value here will force the addition of an
322 * appropriate 'token' parameter in self::getFinalParams(). Also,
323 * self::mustBePosted() must return true when tokens are used.
325 * In previous versions of MediaWiki, true was a valid return value.
326 * Returning true will generate errors indicating that the API module needs
329 * @return string|false
331 public function needsToken() {
336 * Fetch the salt used in the Web UI corresponding to this module.
338 * Only override this if the Web UI uses a token with a non-constant salt.
341 * @param array $params All supplied parameters for the module
342 * @return string|array|null
344 protected function getWebUITokenSalt( array $params ) {
350 /************************************************************************//**
351 * @name Data access methods
356 * Get the name of the module being executed by this instance
359 public function getModuleName() {
360 return $this->mModuleName
;
364 * Get parameter prefix (usually two letters or an empty string).
367 public function getModulePrefix() {
368 return $this->mModulePrefix
;
372 * Get the main module
375 public function getMain() {
376 return $this->mMainModule
;
380 * Returns true if this module is the main module ($this === $this->mMainModule),
384 public function isMain() {
385 return $this === $this->mMainModule
;
389 * Get the parent of this module
391 * @return ApiBase|null
393 public function getParent() {
394 return $this->isMain() ?
null : $this->getMain();
398 * Returns true if the current request breaks the same-origin policy.
400 * For example, json with callbacks.
402 * https://en.wikipedia.org/wiki/Same-origin_policy
407 public function lacksSameOriginSecurity() {
408 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
412 * Get the path to this module
417 public function getModulePath() {
418 if ( $this->isMain() ) {
420 } elseif ( $this->getParent()->isMain() ) {
421 return $this->getModuleName();
423 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
428 * Get a module from its module path
431 * @param string $path
432 * @return ApiBase|null
433 * @throws UsageException
435 public function getModuleFromPath( $path ) {
436 $module = $this->getMain();
437 if ( $path === 'main' ) {
441 $parts = explode( '+', $path );
442 if ( count( $parts ) === 1 ) {
443 // In case the '+' was typed into URL, it resolves as a space
444 $parts = explode( ' ', $path );
447 $count = count( $parts );
448 for ( $i = 0; $i < $count; $i++
) {
450 $manager = $parent->getModuleManager();
451 if ( $manager === null ) {
452 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
453 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
455 $module = $manager->getModule( $parts[$i] );
457 if ( $module === null ) {
458 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
460 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
470 * Get the result object
473 public function getResult() {
474 // Main module has getResult() method overridden
475 // Safety - avoid infinite loop:
476 if ( $this->isMain() ) {
477 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
480 return $this->getMain()->getResult();
484 * Get the error formatter
485 * @return ApiErrorFormatter
487 public function getErrorFormatter() {
488 // Main module has getErrorFormatter() method overridden
489 // Safety - avoid infinite loop:
490 if ( $this->isMain() ) {
491 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
494 return $this->getMain()->getErrorFormatter();
498 * Gets a default slave database connection object
499 * @return DatabaseBase
501 protected function getDB() {
502 if ( !isset( $this->mSlaveDB
) ) {
503 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
506 return $this->mSlaveDB
;
510 * Get the continuation manager
511 * @return ApiContinuationManager|null
513 public function getContinuationManager() {
514 // Main module has getContinuationManager() method overridden
515 // Safety - avoid infinite loop:
516 if ( $this->isMain() ) {
517 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
520 return $this->getMain()->getContinuationManager();
524 * Set the continuation manager
525 * @param ApiContinuationManager|null
527 public function setContinuationManager( $manager ) {
528 // Main module has setContinuationManager() method overridden
529 // Safety - avoid infinite loop:
530 if ( $this->isMain() ) {
531 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
534 $this->getMain()->setContinuationManager( $manager );
539 /************************************************************************//**
540 * @name Parameter handling
545 * This method mangles parameter name based on the prefix supplied to the constructor.
546 * Override this method to change parameter name during runtime
547 * @param string $paramName Parameter name
548 * @return string Prefixed parameter name
550 public function encodeParamName( $paramName ) {
551 return $this->mModulePrefix
. $paramName;
555 * Using getAllowedParams(), this function makes an array of the values
556 * provided by the user, with key being the name of the variable, and
557 * value - validated value from user or default. limits will not be
558 * parsed if $parseLimit is set to false; use this when the max
559 * limit is not definitive yet, e.g. when getting revisions.
560 * @param bool $parseLimit True by default
563 public function extractRequestParams( $parseLimit = true ) {
564 // Cache parameters, for performance and to avoid bug 24564.
565 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
566 $params = $this->getFinalParams();
569 if ( $params ) { // getFinalParams() can return false
570 foreach ( $params as $paramName => $paramSettings ) {
571 $results[$paramName] = $this->getParameterFromSettings(
572 $paramName, $paramSettings, $parseLimit );
575 $this->mParamCache
[$parseLimit] = $results;
578 return $this->mParamCache
[$parseLimit];
582 * Get a value for the given parameter
583 * @param string $paramName Parameter name
584 * @param bool $parseLimit See extractRequestParams()
585 * @return mixed Parameter value
587 protected function getParameter( $paramName, $parseLimit = true ) {
588 $params = $this->getFinalParams();
589 $paramSettings = $params[$paramName];
591 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
595 * Die if none or more than one of a certain set of parameters is set and not false.
597 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
598 * @param string $required,... Names of parameters of which exactly one must be set
600 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
601 $required = func_get_args();
602 array_shift( $required );
603 $p = $this->getModulePrefix();
605 $intersection = array_intersect( array_keys( array_filter( $params,
606 array( $this, "parameterNotEmpty" ) ) ), $required );
608 if ( count( $intersection ) > 1 ) {
610 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
612 } elseif ( count( $intersection ) == 0 ) {
614 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
621 * Die if more than one of a certain set of parameters is set and not false.
623 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
624 * @param string $required,... Names of parameters of which at most one must be set
626 public function requireMaxOneParameter( $params, $required /*...*/ ) {
627 $required = func_get_args();
628 array_shift( $required );
629 $p = $this->getModulePrefix();
631 $intersection = array_intersect( array_keys( array_filter( $params,
632 array( $this, "parameterNotEmpty" ) ) ), $required );
634 if ( count( $intersection ) > 1 ) {
636 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
643 * Die if none of a certain set of parameters is set and not false.
646 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
647 * @param string $required,... Names of parameters of which at least one must be set
649 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
650 $required = func_get_args();
651 array_shift( $required );
652 $p = $this->getModulePrefix();
654 $intersection = array_intersect(
655 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
659 if ( count( $intersection ) == 0 ) {
660 $this->dieUsage( "At least one of the parameters {$p}" .
661 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
666 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
668 * @param object $x Parameter to check is not null/false
671 private function parameterNotEmpty( $x ) {
672 return !is_null( $x ) && $x !== false;
676 * Get a WikiPage object from a title or pageid param, if possible.
677 * Can die, if no param is set or if the title or page id is not valid.
679 * @param array $params
680 * @param bool|string $load Whether load the object's state from the database:
681 * - false: don't load (if the pageid is given, it will still be loaded)
682 * - 'fromdb': load from a slave database
683 * - 'fromdbmaster': load from the master database
686 public function getTitleOrPageId( $params, $load = false ) {
687 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
690 if ( isset( $params['title'] ) ) {
691 $titleObj = Title
::newFromText( $params['title'] );
692 if ( !$titleObj ||
$titleObj->isExternal() ) {
693 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
695 if ( !$titleObj->canExist() ) {
696 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
698 $pageObj = WikiPage
::factory( $titleObj );
699 if ( $load !== false ) {
700 $pageObj->loadPageData( $load );
702 } elseif ( isset( $params['pageid'] ) ) {
703 if ( $load === false ) {
706 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
708 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
716 * Return true if we're to watch the page, false if not, null if no change.
717 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
718 * @param Title $titleObj The page under consideration
719 * @param string $userOption The user option to consider when $watchlist=preferences.
720 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
723 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
725 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
727 switch ( $watchlist ) {
735 # If the user is already watching, don't bother checking
736 if ( $userWatching ) {
739 # If no user option was passed, use watchdefault and watchcreations
740 if ( is_null( $userOption ) ) {
741 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
742 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
745 # Watch the article based on the user preference
746 return $this->getUser()->getBoolOption( $userOption );
749 return $userWatching;
752 return $userWatching;
757 * Using the settings determine the value for the given parameter
759 * @param string $paramName Parameter name
760 * @param array|mixed $paramSettings Default value or an array of settings
761 * using PARAM_* constants.
762 * @param bool $parseLimit Parse limit?
763 * @return mixed Parameter value
765 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
766 // Some classes may decide to change parameter names
767 $encParamName = $this->encodeParamName( $paramName );
769 if ( !is_array( $paramSettings ) ) {
770 $default = $paramSettings;
772 $type = gettype( $paramSettings );
777 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
778 ?
$paramSettings[self
::PARAM_DFLT
]
780 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
781 ?
$paramSettings[self
::PARAM_ISMULTI
]
783 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
784 ?
$paramSettings[self
::PARAM_TYPE
]
786 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
787 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
789 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
790 ?
$paramSettings[self
::PARAM_DEPRECATED
]
792 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
793 ?
$paramSettings[self
::PARAM_REQUIRED
]
796 // When type is not given, and no choices, the type is the same as $default
797 if ( !isset( $type ) ) {
798 if ( isset( $default ) ) {
799 $type = gettype( $default );
801 $type = 'NULL'; // allow everything
806 if ( $type == 'boolean' ) {
807 if ( isset( $default ) && $default !== false ) {
808 // Having a default value of anything other than 'false' is not allowed
811 "Boolean param $encParamName's default is set to '$default'. " .
812 "Boolean parameters must default to false."
816 $value = $this->getMain()->getCheck( $encParamName );
817 } elseif ( $type == 'upload' ) {
818 if ( isset( $default ) ) {
819 // Having a default value is not allowed
822 "File upload param $encParamName's default is set to " .
823 "'$default'. File upload parameters may not have a default." );
826 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
828 $value = $this->getMain()->getUpload( $encParamName );
829 if ( !$value->exists() ) {
830 // This will get the value without trying to normalize it
831 // (because trying to normalize a large binary file
832 // accidentally uploaded as a field fails spectacularly)
833 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
834 if ( $value !== null ) {
836 "File upload param $encParamName is not a file upload; " .
837 "be sure to use multipart/form-data for your POST and include " .
838 "a filename in the Content-Disposition header.",
839 "badupload_{$encParamName}"
844 $value = $this->getMain()->getVal( $encParamName, $default );
846 if ( isset( $value ) && $type == 'namespace' ) {
847 $type = MWNamespace
::getValidNamespaces();
849 if ( isset( $value ) && $type == 'submodule' ) {
850 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
851 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
853 $type = $this->getModuleManager()->getNames( $paramName );
858 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
859 $value = $this->parseMultiValue(
863 is_array( $type ) ?
$type : null
867 // More validation only when choices were not given
868 // choices were validated in parseMultiValue()
869 if ( isset( $value ) ) {
870 if ( !is_array( $type ) ) {
872 case 'NULL': // nothing to do
877 if ( $required && $value === '' ) {
878 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
881 case 'integer': // Force everything using intval() and optionally validate limits
882 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
883 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
884 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
885 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
887 if ( is_array( $value ) ) {
888 $value = array_map( 'intval', $value );
889 if ( !is_null( $min ) ||
!is_null( $max ) ) {
890 foreach ( $value as &$v ) {
891 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
895 $value = intval( $value );
896 if ( !is_null( $min ) ||
!is_null( $max ) ) {
897 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
902 if ( !$parseLimit ) {
903 // Don't do any validation whatsoever
906 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
907 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
911 "MAX1 or MAX2 are not defined for the limit $encParamName"
915 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
917 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
918 if ( $value == 'max' ) {
919 $value = $this->getMain()->canApiHighLimits()
920 ?
$paramSettings[self
::PARAM_MAX2
]
921 : $paramSettings[self
::PARAM_MAX
];
922 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
924 $value = intval( $value );
925 $this->validateLimit(
929 $paramSettings[self
::PARAM_MAX
],
930 $paramSettings[self
::PARAM_MAX2
]
936 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
940 if ( is_array( $value ) ) {
941 foreach ( $value as $key => $val ) {
942 $value[$key] = $this->validateTimestamp( $val, $encParamName );
945 $value = $this->validateTimestamp( $value, $encParamName );
949 if ( is_array( $value ) ) {
950 foreach ( $value as $key => $val ) {
951 $value[$key] = $this->validateUser( $val, $encParamName );
954 $value = $this->validateUser( $value, $encParamName );
957 case 'upload': // nothing to do
960 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
964 // Throw out duplicates if requested
965 if ( !$dupes && is_array( $value ) ) {
966 $value = array_unique( $value );
969 // Set a warning if a deprecated parameter has been passed
970 if ( $deprecated && $value !== false ) {
971 $this->setWarning( "The $encParamName parameter has been deprecated." );
973 } elseif ( $required ) {
974 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
981 * Return an array of values that were given in a 'a|b|c' notation,
982 * after it optionally validates them against the list allowed values.
984 * @param string $valueName The name of the parameter (for error
986 * @param mixed $value The value being parsed
987 * @param bool $allowMultiple Can $value contain more than one value
989 * @param string[]|null $allowedValues An array of values to check against. If
990 * null, all values are accepted.
991 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
993 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
994 if ( trim( $value ) === '' && $allowMultiple ) {
998 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
999 // because it unstubs $wgUser
1000 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1001 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1005 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1006 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1007 "the limit is $sizeLimit" );
1010 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1011 // Bug 33482 - Allow entries with | in them for non-multiple values
1012 if ( in_array( $value, $allowedValues, true ) ) {
1016 $possibleValues = is_array( $allowedValues )
1017 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1020 "Only one $possibleValues is allowed for parameter '$valueName'",
1021 "multival_$valueName"
1025 if ( is_array( $allowedValues ) ) {
1026 // Check for unknown values
1027 $unknown = array_diff( $valuesList, $allowedValues );
1028 if ( count( $unknown ) ) {
1029 if ( $allowMultiple ) {
1030 $s = count( $unknown ) > 1 ?
's' : '';
1031 $vals = implode( ", ", $unknown );
1032 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1035 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1036 "unknown_$valueName"
1040 // Now throw them out
1041 $valuesList = array_intersect( $valuesList, $allowedValues );
1044 return $allowMultiple ?
$valuesList : $valuesList[0];
1048 * Validate the value against the minimum and user/bot maximum limits.
1049 * Prints usage info on failure.
1050 * @param string $paramName Parameter name
1051 * @param int $value Parameter value
1052 * @param int|null $min Minimum value
1053 * @param int|null $max Maximum value for users
1054 * @param int $botMax Maximum value for sysops/bots
1055 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1057 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1058 if ( !is_null( $min ) && $value < $min ) {
1059 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1060 $this->warnOrDie( $msg, $enforceLimits );
1064 // Minimum is always validated, whereas maximum is checked only if not
1065 // running in internal call mode
1066 if ( $this->getMain()->isInternalMode() ) {
1070 // Optimization: do not check user's bot status unless really needed -- skips db query
1071 // assumes $botMax >= $max
1072 if ( !is_null( $max ) && $value > $max ) {
1073 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1074 if ( $value > $botMax ) {
1075 $msg = $this->encodeParamName( $paramName ) .
1076 " may not be over $botMax (set to $value) for bots or sysops";
1077 $this->warnOrDie( $msg, $enforceLimits );
1081 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1082 $this->warnOrDie( $msg, $enforceLimits );
1089 * Validate and normalize of parameters of type 'timestamp'
1090 * @param string $value Parameter value
1091 * @param string $encParamName Parameter name
1092 * @return string Validated and normalized parameter
1094 protected function validateTimestamp( $value, $encParamName ) {
1095 // Confusing synonyms for the current time accepted by wfTimestamp()
1096 // (wfTimestamp() also accepts various non-strings and the string of 14
1097 // ASCII NUL bytes, but those can't get here)
1099 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1101 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1102 ' If for some reason you need to explicitly specify the current time without' .
1103 ' calculating it client-side, use "now".'
1105 return wfTimestamp( TS_MW
);
1108 // Explicit synonym for the current time
1109 if ( $value === 'now' ) {
1110 return wfTimestamp( TS_MW
);
1113 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1114 if ( $unixTimestamp === false ) {
1116 "Invalid value '$value' for timestamp parameter $encParamName",
1117 "badtimestamp_{$encParamName}"
1121 return wfTimestamp( TS_MW
, $unixTimestamp );
1125 * Validate the supplied token.
1128 * @param string $token Supplied token
1129 * @param array $params All supplied parameters for the module
1131 * @throws MWException
1133 final public function validateToken( $token, array $params ) {
1134 $tokenType = $this->needsToken();
1135 $salts = ApiQueryTokens
::getTokenTypeSalts();
1136 if ( !isset( $salts[$tokenType] ) ) {
1137 throw new MWException(
1138 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1139 'without registering it'
1143 if ( $this->getUser()->matchEditToken(
1151 $webUiSalt = $this->getWebUITokenSalt( $params );
1152 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1164 * Validate and normalize of parameters of type 'user'
1165 * @param string $value Parameter value
1166 * @param string $encParamName Parameter name
1167 * @return string Validated and normalized parameter
1169 private function validateUser( $value, $encParamName ) {
1170 $title = Title
::makeTitleSafe( NS_USER
, $value );
1171 if ( $title === null ) {
1173 "Invalid value '$value' for user parameter $encParamName",
1174 "baduser_{$encParamName}"
1178 return $title->getText();
1183 /************************************************************************//**
1184 * @name Utility methods
1189 * Set a watch (or unwatch) based the based on a watchlist parameter.
1190 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1191 * @param Title $titleObj The article's title to change
1192 * @param string $userOption The user option to consider when $watch=preferences
1194 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1195 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1196 if ( $value === null ) {
1200 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1204 * Truncate an array to a certain length.
1205 * @param array $arr Array to truncate
1206 * @param int $limit Maximum length
1207 * @return bool True if the array was truncated, false otherwise
1209 public static function truncateArray( &$arr, $limit ) {
1211 while ( count( $arr ) > $limit ) {
1220 * Gets the user for whom to get the watchlist
1222 * @param array $params
1225 public function getWatchlistUser( $params ) {
1226 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1227 $user = User
::newFromName( $params['owner'], false );
1228 if ( !( $user && $user->getId() ) ) {
1229 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1231 $token = $user->getOption( 'watchlisttoken' );
1232 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1234 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1239 if ( !$this->getUser()->isLoggedIn() ) {
1240 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1242 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1243 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1245 $user = $this->getUser();
1252 * A subset of wfEscapeWikiText for BC texts
1255 * @param string|array $v
1256 * @return string|array
1258 private static function escapeWikiText( $v ) {
1259 if ( is_array( $v ) ) {
1260 return array_map( 'self::escapeWikiText', $v );
1262 return strtr( $v, array(
1263 '__' => '__', '{' => '{', '}' => '}',
1264 '[[Category:' => '[[:Category:',
1265 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1271 * Create a Message from a string or array
1273 * A string is used as a message key. An array has the message key as the
1274 * first value and message parameters as subsequent values.
1277 * @param string|array|Message $msg
1278 * @param IContextSource $context
1279 * @param array $params
1280 * @return Message|null
1282 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1283 if ( is_string( $msg ) ) {
1284 $msg = wfMessage( $msg );
1285 } elseif ( is_array( $msg ) ) {
1286 $msg = call_user_func_array( 'wfMessage', $msg );
1288 if ( !$msg instanceof Message
) {
1292 $msg->setContext( $context );
1294 $msg->params( $params );
1302 /************************************************************************//**
1303 * @name Warning and error reporting
1308 * Set warning section for this module. Users should monitor this
1309 * section to notice any changes in API. Multiple calls to this
1310 * function will result in the warning messages being separated by
1312 * @param string $warning Warning message
1314 public function setWarning( $warning ) {
1315 $msg = new ApiRawMessage( $warning, 'warning' );
1316 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1320 * Adds a warning to the output, else dies
1322 * @param string $msg Message to show as a warning, or error message if dying
1323 * @param bool $enforceLimits Whether this is an enforce (die)
1325 private function warnOrDie( $msg, $enforceLimits = false ) {
1326 if ( $enforceLimits ) {
1327 $this->dieUsage( $msg, 'integeroutofrange' );
1330 $this->setWarning( $msg );
1334 * Throw a UsageException, which will (if uncaught) call the main module's
1335 * error handler and die with an error message.
1337 * @param string $description One-line human-readable description of the
1338 * error condition, e.g., "The API requires a valid action parameter"
1339 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1340 * automated identification of the error, e.g., 'unknown_action'
1341 * @param int $httpRespCode HTTP response code
1342 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1343 * @throws UsageException
1345 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1346 throw new UsageException(
1348 $this->encodeParamName( $errorCode ),
1355 * Get error (as code, string) from a Status object.
1358 * @param Status $status
1359 * @return array Array of code and error string
1360 * @throws MWException
1362 public function getErrorFromStatus( $status ) {
1363 if ( $status->isGood() ) {
1364 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1367 $errors = $status->getErrorsArray();
1369 // No errors? Assume the warnings should be treated as errors
1370 $errors = $status->getWarningsArray();
1373 // Still no errors? Punt
1374 $errors = array( array( 'unknownerror-nocode' ) );
1377 // Cannot use dieUsageMsg() because extensions might return custom
1379 if ( $errors[0] instanceof Message
) {
1381 $code = $msg->getKey();
1383 $code = array_shift( $errors[0] );
1384 $msg = wfMessage( $code, $errors[0] );
1386 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1387 // Translate message to code, for backwards compatibility
1388 $code = ApiBase
::$messageMap[$code]['code'];
1391 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1395 * Throw a UsageException based on the errors in the Status object.
1398 * @param Status $status
1399 * @throws MWException
1401 public function dieStatus( $status ) {
1403 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1404 $this->dieUsage( $msg, $code );
1407 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1409 * Array that maps message keys to error messages. $1 and friends are replaced.
1411 public static $messageMap = array(
1412 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1413 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1414 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1416 // Messages from Title::getUserPermissionsErrors()
1417 'ns-specialprotected' => array(
1418 'code' => 'unsupportednamespace',
1419 'info' => "Pages in the Special namespace can't be edited"
1421 'protectedinterface' => array(
1422 'code' => 'protectednamespace-interface',
1423 'info' => "You're not allowed to edit interface messages"
1425 'namespaceprotected' => array(
1426 'code' => 'protectednamespace',
1427 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1429 'customcssprotected' => array(
1430 'code' => 'customcssprotected',
1431 'info' => "You're not allowed to edit custom CSS pages"
1433 'customjsprotected' => array(
1434 'code' => 'customjsprotected',
1435 'info' => "You're not allowed to edit custom JavaScript pages"
1437 'cascadeprotected' => array(
1438 'code' => 'cascadeprotected',
1439 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1441 'protectedpagetext' => array(
1442 'code' => 'protectedpage',
1443 'info' => "The \"\$1\" right is required to edit this page"
1445 'protect-cantedit' => array(
1446 'code' => 'cantedit',
1447 'info' => "You can't protect this page because you can't edit it"
1449 'deleteprotected' => array(
1450 'code' => 'cantedit',
1451 'info' => "You can't delete this page because it has been protected"
1453 'badaccess-group0' => array(
1454 'code' => 'permissiondenied',
1455 'info' => "Permission denied"
1456 ), // Generic permission denied message
1457 'badaccess-groups' => array(
1458 'code' => 'permissiondenied',
1459 'info' => "Permission denied"
1461 'titleprotected' => array(
1462 'code' => 'protectedtitle',
1463 'info' => "This title has been protected from creation"
1465 'nocreate-loggedin' => array(
1466 'code' => 'cantcreate',
1467 'info' => "You don't have permission to create new pages"
1469 'nocreatetext' => array(
1470 'code' => 'cantcreate-anon',
1471 'info' => "Anonymous users can't create new pages"
1473 'movenologintext' => array(
1474 'code' => 'cantmove-anon',
1475 'info' => "Anonymous users can't move pages"
1477 'movenotallowed' => array(
1478 'code' => 'cantmove',
1479 'info' => "You don't have permission to move pages"
1481 'confirmedittext' => array(
1482 'code' => 'confirmemail',
1483 'info' => "You must confirm your email address before you can edit"
1485 'blockedtext' => array(
1486 'code' => 'blocked',
1487 'info' => "You have been blocked from editing"
1489 'autoblockedtext' => array(
1490 'code' => 'autoblocked',
1491 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1494 // Miscellaneous interface messages
1495 'actionthrottledtext' => array(
1496 'code' => 'ratelimited',
1497 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1499 'alreadyrolled' => array(
1500 'code' => 'alreadyrolled',
1501 'info' => "The page you tried to rollback was already rolled back"
1503 'cantrollback' => array(
1504 'code' => 'onlyauthor',
1505 'info' => "The page you tried to rollback only has one author"
1507 'readonlytext' => array(
1508 'code' => 'readonly',
1509 'info' => "The wiki is currently in read-only mode"
1511 'sessionfailure' => array(
1512 'code' => 'badtoken',
1513 'info' => "Invalid token" ),
1514 'cannotdelete' => array(
1515 'code' => 'cantdelete',
1516 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1518 'notanarticle' => array(
1519 'code' => 'missingtitle',
1520 'info' => "The page you requested doesn't exist"
1522 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1524 'immobile_namespace' => array(
1525 'code' => 'immobilenamespace',
1526 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1528 'articleexists' => array(
1529 'code' => 'articleexists',
1530 'info' => "The destination article already exists and is not a redirect to the source article"
1532 'protectedpage' => array(
1533 'code' => 'protectedpage',
1534 'info' => "You don't have permission to perform this move"
1536 'hookaborted' => array(
1537 'code' => 'hookaborted',
1538 'info' => "The modification you tried to make was aborted by an extension hook"
1540 'cantmove-titleprotected' => array(
1541 'code' => 'protectedtitle',
1542 'info' => "The destination article has been protected from creation"
1544 'imagenocrossnamespace' => array(
1545 'code' => 'nonfilenamespace',
1546 'info' => "Can't move a file to a non-file namespace"
1548 'imagetypemismatch' => array(
1549 'code' => 'filetypemismatch',
1550 'info' => "The new file extension doesn't match its type"
1552 // 'badarticleerror' => shouldn't happen
1553 // 'badtitletext' => shouldn't happen
1554 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1555 'range_block_disabled' => array(
1556 'code' => 'rangedisabled',
1557 'info' => "Blocking IP ranges has been disabled"
1559 'nosuchusershort' => array(
1560 'code' => 'nosuchuser',
1561 'info' => "The user you specified doesn't exist"
1563 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1564 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1565 'ipb_already_blocked' => array(
1566 'code' => 'alreadyblocked',
1567 'info' => "The user you tried to block was already blocked"
1569 'ipb_blocked_as_range' => array(
1570 'code' => 'blockedasrange',
1571 '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."
1573 'ipb_cant_unblock' => array(
1574 'code' => 'cantunblock',
1575 'info' => "The block you specified was not found. It may have been unblocked already"
1577 'mailnologin' => array(
1578 'code' => 'cantsend',
1579 '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"
1581 'ipbblocked' => array(
1582 'code' => 'ipbblocked',
1583 'info' => 'You cannot block or unblock users while you are yourself blocked'
1585 'ipbnounblockself' => array(
1586 'code' => 'ipbnounblockself',
1587 'info' => 'You are not allowed to unblock yourself'
1589 'usermaildisabled' => array(
1590 'code' => 'usermaildisabled',
1591 'info' => "User email has been disabled"
1593 'blockedemailuser' => array(
1594 'code' => 'blockedfrommail',
1595 'info' => "You have been blocked from sending email"
1597 'notarget' => array(
1598 'code' => 'notarget',
1599 'info' => "You have not specified a valid target for this action"
1602 'code' => 'noemail',
1603 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1605 'rcpatroldisabled' => array(
1606 'code' => 'patroldisabled',
1607 'info' => "Patrolling is disabled on this wiki"
1609 'markedaspatrollederror-noautopatrol' => array(
1610 'code' => 'noautopatrol',
1611 'info' => "You don't have permission to patrol your own changes"
1613 'delete-toobig' => array(
1614 'code' => 'bigdelete',
1615 'info' => "You can't delete this page because it has more than \$1 revisions"
1617 'movenotallowedfile' => array(
1618 'code' => 'cantmovefile',
1619 'info' => "You don't have permission to move files"
1621 'userrights-no-interwiki' => array(
1622 'code' => 'nointerwikiuserrights',
1623 'info' => "You don't have permission to change user rights on other wikis"
1625 'userrights-nodatabase' => array(
1626 'code' => 'nosuchdatabase',
1627 'info' => "Database \"\$1\" does not exist or is not local"
1629 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1630 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1631 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1632 'import-rootpage-invalid' => array(
1633 'code' => 'import-rootpage-invalid',
1634 'info' => 'Root page is an invalid title'
1636 'import-rootpage-nosubpage' => array(
1637 'code' => 'import-rootpage-nosubpage',
1638 'info' => 'Namespace "$1" of the root page does not allow subpages'
1641 // API-specific messages
1642 'readrequired' => array(
1643 'code' => 'readapidenied',
1644 'info' => "You need read permission to use this module"
1646 'writedisabled' => array(
1647 'code' => 'noapiwrite',
1648 '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"
1650 'writerequired' => array(
1651 'code' => 'writeapidenied',
1652 'info' => "You're not allowed to edit this wiki through the API"
1654 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1655 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1656 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1657 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1658 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1659 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1660 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1661 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1662 'create-titleexists' => array(
1663 'code' => 'create-titleexists',
1664 'info' => "Existing titles can't be protected with 'create'"
1666 'missingtitle-createonly' => array(
1667 'code' => 'missingtitle-createonly',
1668 'info' => "Missing titles can only be protected with 'create'"
1670 'cantblock' => array( 'code' => 'cantblock',
1671 'info' => "You don't have permission to block users"
1673 'canthide' => array(
1674 'code' => 'canthide',
1675 'info' => "You don't have permission to hide user names from the block log"
1677 'cantblock-email' => array(
1678 'code' => 'cantblock-email',
1679 'info' => "You don't have permission to block users from sending email through the wiki"
1681 'unblock-notarget' => array(
1682 'code' => 'notarget',
1683 'info' => "Either the id or the user parameter must be set"
1685 'unblock-idanduser' => array(
1686 'code' => 'idanduser',
1687 'info' => "The id and user parameters can't be used together"
1689 'cantunblock' => array(
1690 'code' => 'permissiondenied',
1691 'info' => "You don't have permission to unblock users"
1693 'cannotundelete' => array(
1694 'code' => 'cantundelete',
1695 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1697 'permdenied-undelete' => array(
1698 'code' => 'permissiondenied',
1699 'info' => "You don't have permission to restore deleted revisions"
1701 'createonly-exists' => array(
1702 'code' => 'articleexists',
1703 'info' => "The article you tried to create has been created already"
1705 'nocreate-missing' => array(
1706 'code' => 'missingtitle',
1707 'info' => "The article you tried to edit doesn't exist"
1709 'cantchangecontentmodel' => array(
1710 'code' => 'cantchangecontentmodel',
1711 'info' => "You don't have permission to change the content model of a page"
1713 'nosuchrcid' => array(
1714 'code' => 'nosuchrcid',
1715 'info' => "There is no change with rcid \"\$1\""
1717 'nosuchlogid' => array(
1718 'code' => 'nosuchlogid',
1719 'info' => "There is no log entry with ID \"\$1\""
1721 'protect-invalidaction' => array(
1722 'code' => 'protect-invalidaction',
1723 'info' => "Invalid protection type \"\$1\""
1725 'protect-invalidlevel' => array(
1726 'code' => 'protect-invalidlevel',
1727 'info' => "Invalid protection level \"\$1\""
1729 'toofewexpiries' => array(
1730 'code' => 'toofewexpiries',
1731 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1733 'cantimport' => array(
1734 'code' => 'cantimport',
1735 'info' => "You don't have permission to import pages"
1737 'cantimport-upload' => array(
1738 'code' => 'cantimport-upload',
1739 'info' => "You don't have permission to import uploaded pages"
1741 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1742 'importuploaderrorsize' => array(
1743 'code' => 'filetoobig',
1744 'info' => 'The file you uploaded is bigger than the maximum upload size'
1746 'importuploaderrorpartial' => array(
1747 'code' => 'partialupload',
1748 'info' => 'The file was only partially uploaded'
1750 'importuploaderrortemp' => array(
1751 'code' => 'notempdir',
1752 'info' => 'The temporary upload directory is missing'
1754 'importcantopen' => array(
1755 'code' => 'cantopenfile',
1756 'info' => "Couldn't open the uploaded file"
1758 'import-noarticle' => array(
1759 'code' => 'badinterwiki',
1760 'info' => 'Invalid interwiki title specified'
1762 'importbadinterwiki' => array(
1763 'code' => 'badinterwiki',
1764 'info' => 'Invalid interwiki title specified'
1766 'import-unknownerror' => array(
1767 'code' => 'import-unknownerror',
1768 'info' => "Unknown error on import: \"\$1\""
1770 'cantoverwrite-sharedfile' => array(
1771 'code' => 'cantoverwrite-sharedfile',
1772 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1774 'sharedfile-exists' => array(
1775 'code' => 'fileexists-sharedrepo-perm',
1776 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1778 'mustbeposted' => array(
1779 'code' => 'mustbeposted',
1780 'info' => "The \$1 module requires a POST request"
1784 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1786 'specialpage-cantexecute' => array(
1787 'code' => 'specialpage-cantexecute',
1788 'info' => "You don't have permission to view the results of this special page"
1790 'invalidoldimage' => array(
1791 'code' => 'invalidoldimage',
1792 'info' => 'The oldimage parameter has invalid format'
1794 'nodeleteablefile' => array(
1795 'code' => 'nodeleteablefile',
1796 'info' => 'No such old version of the file'
1798 'fileexists-forbidden' => array(
1799 'code' => 'fileexists-forbidden',
1800 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1802 'fileexists-shared-forbidden' => array(
1803 'code' => 'fileexists-shared-forbidden',
1804 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1806 'filerevert-badversion' => array(
1807 'code' => 'filerevert-badversion',
1808 'info' => 'There is no previous local version of this file with the provided timestamp.'
1811 // ApiEditPage messages
1812 'noimageredirect-anon' => array(
1813 'code' => 'noimageredirect-anon',
1814 'info' => "Anonymous users can't create image redirects"
1816 'noimageredirect-logged' => array(
1817 'code' => 'noimageredirect',
1818 'info' => "You don't have permission to create image redirects"
1820 'spamdetected' => array(
1821 'code' => 'spamdetected',
1822 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1824 'contenttoobig' => array(
1825 'code' => 'contenttoobig',
1826 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1828 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1829 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1830 'wasdeleted' => array(
1831 'code' => 'pagedeleted',
1832 'info' => "The page has been deleted since you fetched its timestamp"
1834 'blankpage' => array(
1835 'code' => 'emptypage',
1836 'info' => "Creating new, empty pages is not allowed"
1838 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1839 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1840 'missingtext' => array(
1842 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1844 'emptynewsection' => array(
1845 'code' => 'emptynewsection',
1846 'info' => 'Creating empty new sections is not possible.'
1848 'revwrongpage' => array(
1849 'code' => 'revwrongpage',
1850 'info' => "r\$1 is not a revision of \"\$2\""
1852 'undo-failure' => array(
1853 'code' => 'undofailure',
1854 'info' => 'Undo failed due to conflicting intermediate edits'
1856 'content-not-allowed-here' => array(
1857 'code' => 'contentnotallowedhere',
1858 'info' => 'Content model "$1" is not allowed at title "$2"'
1861 // Messages from WikiPage::doEit()
1862 'edit-hook-aborted' => array(
1863 'code' => 'edit-hook-aborted',
1864 'info' => "Your edit was aborted by an ArticleSave hook"
1866 'edit-gone-missing' => array(
1867 'code' => 'edit-gone-missing',
1868 'info' => "The page you tried to edit doesn't seem to exist anymore"
1870 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1871 'edit-already-exists' => array(
1872 'code' => 'edit-already-exists',
1873 'info' => 'It seems the page you tried to create already exist'
1877 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1878 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1879 'uploaddisabled' => array(
1880 'code' => 'uploaddisabled',
1881 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1883 'copyuploaddisabled' => array(
1884 'code' => 'copyuploaddisabled',
1885 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1887 'copyuploadbaddomain' => array(
1888 'code' => 'copyuploadbaddomain',
1889 'info' => 'Uploads by URL are not allowed from this domain.'
1891 'copyuploadbadurl' => array(
1892 'code' => 'copyuploadbadurl',
1893 'info' => 'Upload not allowed from this URL.'
1896 'filename-tooshort' => array(
1897 'code' => 'filename-tooshort',
1898 'info' => 'The filename is too short'
1900 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1901 'illegal-filename' => array(
1902 'code' => 'illegal-filename',
1903 'info' => 'The filename is not allowed'
1905 'filetype-missing' => array(
1906 'code' => 'filetype-missing',
1907 'info' => 'The file is missing an extension'
1910 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1912 // @codingStandardsIgnoreEnd
1915 * Helper function for readonly errors
1917 public function dieReadOnly() {
1918 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1919 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1920 array( 'readonlyreason' => wfReadOnlyReason() ) );
1924 * Output the error message related to a certain array
1925 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1927 public function dieUsageMsg( $error ) {
1928 # most of the time we send a 1 element, so we might as well send it as
1929 # a string and make this an array here.
1930 if ( is_string( $error ) ) {
1931 $error = array( $error );
1933 $parsed = $this->parseMsg( $error );
1934 $this->dieUsage( $parsed['info'], $parsed['code'] );
1938 * Will only set a warning instead of failing if the global $wgDebugAPI
1939 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1940 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1943 public function dieUsageMsgOrDebug( $error ) {
1944 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1945 $this->dieUsageMsg( $error );
1948 if ( is_string( $error ) ) {
1949 $error = array( $error );
1951 $parsed = $this->parseMsg( $error );
1952 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1956 * Die with the $prefix.'badcontinue' error. This call is common enough to
1957 * make it into the base method.
1958 * @param bool $condition Will only die if this value is true
1961 protected function dieContinueUsageIf( $condition ) {
1964 'Invalid continue param. You should pass the original value returned by the previous query',
1970 * Return the error message related to a certain array
1971 * @param array $error Element of a getUserPermissionsErrors()-style array
1972 * @return array('code' => code, 'info' => info)
1974 public function parseMsg( $error ) {
1975 $error = (array)$error; // It seems strings sometimes make their way in here
1976 $key = array_shift( $error );
1978 // Check whether the error array was nested
1979 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1980 if ( is_array( $key ) ) {
1982 $key = array_shift( $error );
1985 if ( isset( self
::$messageMap[$key] ) ) {
1987 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1988 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1992 // If the key isn't present, throw an "unknown error"
1993 return $this->parseMsg( array( 'unknownerror', $key ) );
1997 * Internal code errors should be reported with this method
1998 * @param string $method Method or function name
1999 * @param string $message Error message
2000 * @throws MWException
2002 protected static function dieDebug( $method, $message ) {
2003 throw new MWException( "Internal error in $method: $message" );
2007 * Write logging information for API features to a debug log, for usage
2009 * @param string $feature Feature being used.
2011 protected function logFeatureUsage( $feature ) {
2012 $request = $this->getRequest();
2013 $s = '"' . addslashes( $feature ) . '"' .
2014 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2015 ' "' . $request->getIP() . '"' .
2016 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2017 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2018 wfDebugLog( 'api-feature-usage', $s, 'private' );
2023 /************************************************************************//**
2024 * @name Help message generation
2029 * Return the description message.
2031 * @return string|array|Message
2033 protected function getDescriptionMessage() {
2034 return "apihelp-{$this->getModulePath()}-description";
2038 * Get final module description, after hooks have had a chance to tweak it as
2041 * @since 1.25, returns Message[] rather than string[]
2044 public function getFinalDescription() {
2045 $desc = $this->getDescription();
2046 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2047 $desc = self
::escapeWikiText( $desc );
2048 if ( is_array( $desc ) ) {
2049 $desc = join( "\n", $desc );
2051 $desc = (string)$desc;
2054 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2055 $this->getModulePrefix(),
2056 $this->getModuleName(),
2057 $this->getModulePath(),
2059 if ( !$msg->exists() ) {
2060 $msg = $this->msg( 'api-help-fallback-description', $desc );
2062 $msgs = array( $msg );
2064 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2070 * Get final list of parameters, after hooks have had a chance to
2071 * tweak it as needed.
2073 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2074 * @return array|bool False on no parameters
2075 * @since 1.21 $flags param added
2077 public function getFinalParams( $flags = 0 ) {
2078 $params = $this->getAllowedParams( $flags );
2083 if ( $this->needsToken() ) {
2084 $params['token'] = array(
2085 ApiBase
::PARAM_TYPE
=> 'string',
2086 ApiBase
::PARAM_REQUIRED
=> true,
2087 ApiBase
::PARAM_HELP_MSG
=> array(
2088 'api-help-param-token',
2089 $this->needsToken(),
2091 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2094 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2100 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2103 * @since 1.25, returns array of Message[] rather than array of string[]
2104 * @return array Keys are parameter names, values are arrays of Message objects
2106 public function getFinalParamDescription() {
2107 $prefix = $this->getModulePrefix();
2108 $name = $this->getModuleName();
2109 $path = $this->getModulePath();
2111 $desc = $this->getParamDescription();
2112 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2117 $desc = self
::escapeWikiText( $desc );
2119 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2121 foreach ( $params as $param => $settings ) {
2122 if ( !is_array( $settings ) ) {
2123 $settings = array();
2126 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2127 if ( is_array( $d ) ) {
2128 // Special handling for prop parameters
2129 $d = array_map( function ( $line ) {
2130 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2131 $line = "\n;{$m[1]}:{$m[2]}";
2135 $d = join( ' ', $d );
2138 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2139 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2141 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2142 if ( !$msg->exists() ) {
2143 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2146 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2147 array( $prefix, $param, $name, $path ) );
2149 $this->dieDebug( __METHOD__
,
2150 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2152 $msgs[$param] = array( $msg );
2154 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2155 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2156 $this->dieDebug( __METHOD__
,
2157 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2159 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2160 $this->dieDebug( __METHOD__
,
2161 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2162 'ApiBase::PARAM_TYPE is an array' );
2165 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2166 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2167 if ( isset( $valueMsgs[$value] ) ) {
2168 $msg = $valueMsgs[$value];
2170 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2172 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2173 array( $prefix, $param, $name, $path, $value ) );
2175 $m = new ApiHelpParamValueMessage(
2177 array( $m->getKey(), 'api-help-param-no-description' ),
2180 $msgs[$param][] = $m->setContext( $this->getContext() );
2182 $this->dieDebug( __METHOD__
,
2183 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2188 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2189 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2190 $this->dieDebug( __METHOD__
,
2191 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2193 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2194 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2195 array( $prefix, $param, $name, $path ) );
2197 $msgs[$param][] = $m;
2199 $this->dieDebug( __METHOD__
,
2200 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2206 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2212 * Generates the list of flags for the help screen and for action=paraminfo
2214 * Corresponding messages: api-help-flag-deprecated,
2215 * api-help-flag-internal, api-help-flag-readrights,
2216 * api-help-flag-writerights, api-help-flag-mustbeposted
2220 protected function getHelpFlags() {
2223 if ( $this->isDeprecated() ) {
2224 $flags[] = 'deprecated';
2226 if ( $this->isInternal() ) {
2227 $flags[] = 'internal';
2229 if ( $this->isReadMode() ) {
2230 $flags[] = 'readrights';
2232 if ( $this->isWriteMode() ) {
2233 $flags[] = 'writerights';
2235 if ( $this->mustBePosted() ) {
2236 $flags[] = 'mustbeposted';
2243 * Returns information about the source of this module, if known
2245 * Returned array is an array with the following keys:
2246 * - path: Install path
2247 * - name: Extension name, or "MediaWiki" for core
2248 * - namemsg: (optional) i18n message key for a display name
2249 * - license-name: (optional) Name of license
2251 * @return array|null
2253 protected function getModuleSourceInfo() {
2256 if ( $this->mModuleSource
!== false ) {
2257 return $this->mModuleSource
;
2260 // First, try to find where the module comes from...
2261 $rClass = new ReflectionClass( $this );
2262 $path = $rClass->getFileName();
2265 $this->mModuleSource
= null;
2268 $path = realpath( $path ) ?
: $path;
2270 // Build map of extension directories to extension info
2271 if ( self
::$extensionInfo === null ) {
2272 self
::$extensionInfo = array(
2273 realpath( __DIR__
) ?
: __DIR__
=> array(
2275 'name' => 'MediaWiki',
2276 'license-name' => 'GPL-2.0+',
2278 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2284 'license-name' => null,
2286 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2287 foreach ( $group as $ext ) {
2288 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2289 // This shouldn't happen, but does anyway.
2293 $extpath = $ext['path'];
2294 if ( !is_dir( $extpath ) ) {
2295 $extpath = dirname( $extpath );
2297 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2298 array_intersect_key( $ext, $keep );
2301 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2302 $extpath = $ext['path'];
2303 if ( !is_dir( $extpath ) ) {
2304 $extpath = dirname( $extpath );
2306 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2307 array_intersect_key( $ext, $keep );
2311 // Now traverse parent directories until we find a match or run out of
2314 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2316 $this->mModuleSource
= self
::$extensionInfo[$path];
2317 return $this->mModuleSource
;
2321 $path = dirname( $path );
2322 } while ( $path !== $oldpath );
2324 // No idea what extension this might be.
2325 $this->mModuleSource
= null;
2330 * Called from ApiHelp before the pieces are joined together and returned.
2332 * This exists mainly for ApiMain to add the Permissions and Credits
2333 * sections. Other modules probably don't need it.
2335 * @param string[] &$help Array of help data
2336 * @param array $options Options passed to ApiHelp::getHelp
2337 * @param array &$tocData If a TOC is being generated, this array has keys
2338 * as anchors in the page and values as for Linker::generateTOC().
2340 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2345 /************************************************************************//**
2350 /// @deprecated since 1.24
2351 const PROP_ROOT
= 'ROOT';
2352 /// @deprecated since 1.24
2353 const PROP_LIST
= 'LIST';
2354 /// @deprecated since 1.24
2355 const PROP_TYPE
= 0;
2356 /// @deprecated since 1.24
2357 const PROP_NULLABLE
= 1;
2360 * Formerly returned a string that identifies the version of the extending
2361 * class. Typically included the class name, the svn revision, timestamp,
2362 * and last author. Usually done with SVN's Id keyword
2364 * @deprecated since 1.21, version string is no longer supported
2367 public function getVersion() {
2368 wfDeprecated( __METHOD__
, '1.21' );
2373 * Formerly used to fetch a list of possible properites in the result,
2374 * somehow organized with respect to the prop parameter that causes them to
2375 * be returned. The specific semantics of the return value was never
2376 * specified. Since this was never possible to be accurately updated, it
2379 * @deprecated since 1.24
2380 * @return array|bool
2382 protected function getResultProperties() {
2383 wfDeprecated( __METHOD__
, '1.24' );
2388 * @see self::getResultProperties()
2389 * @deprecated since 1.24
2390 * @return array|bool
2392 public function getFinalResultProperties() {
2393 wfDeprecated( __METHOD__
, '1.24' );
2398 * @see self::getResultProperties()
2399 * @deprecated since 1.24
2401 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2402 wfDeprecated( __METHOD__
, '1.24' );
2406 * @see self::getPossibleErrors()
2407 * @deprecated since 1.24
2410 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2411 wfDeprecated( __METHOD__
, '1.24' );
2416 * @see self::getPossibleErrors()
2417 * @deprecated since 1.24
2420 public function getRequireMaxOneParameterErrorMessages( $params ) {
2421 wfDeprecated( __METHOD__
, '1.24' );
2426 * @see self::getPossibleErrors()
2427 * @deprecated since 1.24
2430 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2431 wfDeprecated( __METHOD__
, '1.24' );
2436 * @see self::getPossibleErrors()
2437 * @deprecated since 1.24
2440 public function getTitleOrPageIdErrorMessage() {
2441 wfDeprecated( __METHOD__
, '1.24' );
2446 * This formerly attempted to return a list of all possible errors returned
2447 * by the module. However, this was impossible to maintain in many cases
2448 * since errors could come from other areas of MediaWiki and in some cases
2449 * from arbitrary extension hooks. Since a partial list claiming to be
2450 * comprehensive is unlikely to be useful, it was removed.
2452 * @deprecated since 1.24
2455 public function getPossibleErrors() {
2456 wfDeprecated( __METHOD__
, '1.24' );
2461 * @see self::getPossibleErrors()
2462 * @deprecated since 1.24
2465 public function getFinalPossibleErrors() {
2466 wfDeprecated( __METHOD__
, '1.24' );
2471 * @see self::getPossibleErrors()
2472 * @deprecated since 1.24
2475 public function parseErrors( $errors ) {
2476 wfDeprecated( __METHOD__
, '1.24' );
2481 * Returns the description string for this module
2483 * Ignored if an i18n message exists for
2484 * "apihelp-{$this->getModulePath()}-description".
2486 * @deprecated since 1.25
2487 * @return Message|string|array
2489 protected function getDescription() {
2494 * Returns an array of parameter descriptions.
2496 * For each parameter, ignored if an i18n message exists for the parameter.
2497 * By default that message is
2498 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2499 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2500 * self::getFinalParams().
2502 * @deprecated since 1.25
2503 * @return array|bool False on no parameter descriptions
2505 protected function getParamDescription() {
2510 * Returns usage examples for this module.
2512 * Return value as an array is either:
2513 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2515 * - sequential numeric keys with even-numbered keys being display-text
2516 * and odd-numbered keys being partial urls
2517 * - partial URLs as keys with display-text (string or array-to-be-joined)
2519 * Return value as a string is the same as an array with a numeric key and
2520 * that value, and boolean false means "no examples".
2522 * @deprecated since 1.25, use getExamplesMessages() instead
2523 * @return bool|string|array
2525 protected function getExamples() {
2530 * Generates help message for this module, or false if there is no description
2531 * @deprecated since 1.25
2532 * @return string|bool
2534 public function makeHelpMsg() {
2535 wfDeprecated( __METHOD__
, '1.25' );
2536 static $lnPrfx = "\n ";
2538 $msg = $this->getFinalDescription();
2540 if ( $msg !== false ) {
2542 if ( !is_array( $msg ) ) {
2547 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2549 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2551 if ( $this->isReadMode() ) {
2552 $msg .= "\nThis module requires read rights";
2554 if ( $this->isWriteMode() ) {
2555 $msg .= "\nThis module requires write rights";
2557 if ( $this->mustBePosted() ) {
2558 $msg .= "\nThis module only accepts POST requests";
2560 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2561 $this->mustBePosted()
2567 $paramsMsg = $this->makeHelpMsgParameters();
2568 if ( $paramsMsg !== false ) {
2569 $msg .= "Parameters:\n$paramsMsg";
2572 $examples = $this->getExamples();
2574 if ( !is_array( $examples ) ) {
2579 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2580 foreach ( $examples as $k => $v ) {
2581 if ( is_numeric( $k ) ) {
2584 if ( is_array( $v ) ) {
2585 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2587 $msgExample = " $v";
2590 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2600 * @deprecated since 1.25
2601 * @param string $item
2604 private function indentExampleText( $item ) {
2609 * @deprecated since 1.25
2610 * @param string $prefix Text to split output items
2611 * @param string $title What is being output
2612 * @param string|array $input
2615 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2616 wfDeprecated( __METHOD__
, '1.25' );
2617 if ( $input === false ) {
2620 if ( !is_array( $input ) ) {
2621 $input = array( $input );
2624 if ( count( $input ) > 0 ) {
2626 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2630 $msg .= implode( $prefix, $input ) . "\n";
2639 * Generates the parameter descriptions for this module, to be displayed in the
2641 * @deprecated since 1.25
2642 * @return string|bool
2644 public function makeHelpMsgParameters() {
2645 wfDeprecated( __METHOD__
, '1.25' );
2646 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2648 $paramsDescription = $this->getFinalParamDescription();
2650 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2651 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2652 foreach ( $params as $paramName => $paramSettings ) {
2653 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2654 if ( is_array( $desc ) ) {
2655 $desc = implode( $paramPrefix, $desc );
2659 if ( !is_array( $paramSettings ) ) {
2660 $paramSettings = array(
2661 self
::PARAM_DFLT
=> $paramSettings,
2665 //handle missing type
2666 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2667 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2668 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2670 if ( is_bool( $dflt ) ) {
2671 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2672 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2673 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2674 } elseif ( is_int( $dflt ) ) {
2675 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2679 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2680 && $paramSettings[self
::PARAM_DEPRECATED
]
2682 $desc = "DEPRECATED! $desc";
2685 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2686 && $paramSettings[self
::PARAM_REQUIRED
]
2688 $desc .= $paramPrefix . "This parameter is required";
2691 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2692 ?
$paramSettings[self
::PARAM_TYPE
]
2694 if ( isset( $type ) ) {
2695 $hintPipeSeparated = true;
2696 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2697 ?
$paramSettings[self
::PARAM_ISMULTI
]
2700 $prompt = 'Values (separate with \'|\'): ';
2702 $prompt = 'One value: ';
2705 if ( $type === 'submodule' ) {
2706 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2707 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2709 $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 );
2799 * @deprecated since 1.25, always returns empty string
2800 * @param DatabaseBase|bool $db
2803 public function getModuleProfileName( $db = false ) {
2804 wfDeprecated( __METHOD__
, '1.25' );
2809 * @deprecated since 1.25
2811 public function profileIn() {
2812 // No wfDeprecated() yet because extensions call this and might need to
2813 // keep doing so for BC.
2817 * @deprecated since 1.25
2819 public function profileOut() {
2820 // No wfDeprecated() yet because extensions call this and might need to
2821 // keep doing so for BC.
2825 * @deprecated since 1.25
2827 public function safeProfileOut() {
2828 wfDeprecated( __METHOD__
, '1.25' );
2832 * @deprecated since 1.25, always returns 0
2835 public function getProfileTime() {
2836 wfDeprecated( __METHOD__
, '1.25' );
2841 * @deprecated since 1.25
2843 public function profileDBIn() {
2844 wfDeprecated( __METHOD__
, '1.25' );
2848 * @deprecated since 1.25
2850 public function profileDBOut() {
2851 wfDeprecated( __METHOD__
, '1.25' );
2855 * @deprecated since 1.25, always returns 0
2858 public function getProfileDBTime() {
2859 wfDeprecated( __METHOD__
, '1.25' );
2864 * Get the result data array (read-only)
2865 * @deprecated since 1.25, use $this->getResult() methods instead
2868 public function getResultData() {
2869 wfDeprecated( __METHOD__
, '1.25' );
2870 return $this->getResult()->getData();
2874 * Call wfTransactionalTimeLimit() if this request was POSTed
2877 protected function useTransactionalTimeLimit() {
2878 if ( $this->getRequest()->wasPosted() ) {
2879 wfTransactionalTimeLimit();
2887 * For really cool vim folding this needs to be at the end:
2888 * vim: foldmarker=@{,@} foldmethod=marker