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 $examplesCount = count( $examples );
210 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
211 $tmp[$examples[$i +
1]] = $examples[$i];
216 foreach ( $examples as $k => $v ) {
217 if ( is_numeric( $k ) ) {
222 $msg = self
::escapeWikiText( $v );
223 if ( is_array( $msg ) ) {
224 $msg = join( " ", $msg );
228 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
229 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
237 * Return links to more detailed help pages about the module.
238 * @since 1.25, returning boolean false is deprecated
239 * @return string|array
241 public function getHelpUrls() {
246 * Returns an array of allowed parameters (parameter name) => (default
247 * value) or (parameter name) => (array with PARAM_* constants as keys)
248 * Don't call this function directly: use getFinalParams() to allow
249 * hooks to modify parameters as needed.
251 * Some derived classes may choose to handle an integer $flags parameter
252 * in the overriding methods. Callers of this method can pass zero or
253 * more OR-ed flags like GET_VALUES_FOR_HELP.
257 protected function getAllowedParams( /* $flags = 0 */ ) {
258 // int $flags is not declared because it causes "Strict standards"
259 // warning. Most derived classes do not implement it.
264 * Indicates if this module needs maxlag to be checked
267 public function shouldCheckMaxlag() {
272 * Indicates whether this module requires read rights
275 public function isReadMode() {
280 * Indicates whether this module requires write mode
283 public function isWriteMode() {
288 * Indicates whether this module must be called with a POST request
291 public function mustBePosted() {
292 return $this->needsToken() !== false;
296 * Indicates whether this module is deprecated
300 public function isDeprecated() {
305 * Indicates whether this module is "internal"
306 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
310 public function isInternal() {
315 * Returns the token type this module requires in order to execute.
317 * Modules are strongly encouraged to use the core 'csrf' type unless they
318 * have specialized security needs. If the token type is not one of the
319 * core types, you must use the ApiQueryTokensRegisterTypes hook to
322 * Returning a non-falsey value here will force the addition of an
323 * appropriate 'token' parameter in self::getFinalParams(). Also,
324 * self::mustBePosted() must return true when tokens are used.
326 * In previous versions of MediaWiki, true was a valid return value.
327 * Returning true will generate errors indicating that the API module needs
330 * @return string|false
332 public function needsToken() {
337 * Fetch the salt used in the Web UI corresponding to this module.
339 * Only override this if the Web UI uses a token with a non-constant salt.
342 * @param array $params All supplied parameters for the module
343 * @return string|array|null
345 protected function getWebUITokenSalt( array $params ) {
350 * Returns data for HTTP conditional request mechanisms.
353 * @param string $condition Condition being queried:
354 * - last-modified: Return a timestamp representing the maximum of the
355 * last-modified dates for all resources involved in the request. See
356 * RFC 7232 § 2.2 for semantics.
357 * - etag: Return an entity-tag representing the state of all resources involved
358 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
359 * @return string|boolean|null As described above, or null if no value is available.
361 public function getConditionalRequestData( $condition ) {
367 /************************************************************************//**
368 * @name Data access methods
373 * Get the name of the module being executed by this instance
376 public function getModuleName() {
377 return $this->mModuleName
;
381 * Get parameter prefix (usually two letters or an empty string).
384 public function getModulePrefix() {
385 return $this->mModulePrefix
;
389 * Get the main module
392 public function getMain() {
393 return $this->mMainModule
;
397 * Returns true if this module is the main module ($this === $this->mMainModule),
401 public function isMain() {
402 return $this === $this->mMainModule
;
406 * Get the parent of this module
408 * @return ApiBase|null
410 public function getParent() {
411 return $this->isMain() ?
null : $this->getMain();
415 * Returns true if the current request breaks the same-origin policy.
417 * For example, json with callbacks.
419 * https://en.wikipedia.org/wiki/Same-origin_policy
424 public function lacksSameOriginSecurity() {
425 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
429 * Get the path to this module
434 public function getModulePath() {
435 if ( $this->isMain() ) {
437 } elseif ( $this->getParent()->isMain() ) {
438 return $this->getModuleName();
440 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
445 * Get a module from its module path
448 * @param string $path
449 * @return ApiBase|null
450 * @throws UsageException
452 public function getModuleFromPath( $path ) {
453 $module = $this->getMain();
454 if ( $path === 'main' ) {
458 $parts = explode( '+', $path );
459 if ( count( $parts ) === 1 ) {
460 // In case the '+' was typed into URL, it resolves as a space
461 $parts = explode( ' ', $path );
464 $count = count( $parts );
465 for ( $i = 0; $i < $count; $i++
) {
467 $manager = $parent->getModuleManager();
468 if ( $manager === null ) {
469 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
470 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
472 $module = $manager->getModule( $parts[$i] );
474 if ( $module === null ) {
475 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
477 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
487 * Get the result object
490 public function getResult() {
491 // Main module has getResult() method overridden
492 // Safety - avoid infinite loop:
493 if ( $this->isMain() ) {
494 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
497 return $this->getMain()->getResult();
501 * Get the error formatter
502 * @return ApiErrorFormatter
504 public function getErrorFormatter() {
505 // Main module has getErrorFormatter() 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()->getErrorFormatter();
515 * Gets a default slave database connection object
516 * @return DatabaseBase
518 protected function getDB() {
519 if ( !isset( $this->mSlaveDB
) ) {
520 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
523 return $this->mSlaveDB
;
527 * Get the continuation manager
528 * @return ApiContinuationManager|null
530 public function getContinuationManager() {
531 // Main module has getContinuationManager() method overridden
532 // Safety - avoid infinite loop:
533 if ( $this->isMain() ) {
534 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
537 return $this->getMain()->getContinuationManager();
541 * Set the continuation manager
542 * @param ApiContinuationManager|null
544 public function setContinuationManager( $manager ) {
545 // Main module has setContinuationManager() method overridden
546 // Safety - avoid infinite loop:
547 if ( $this->isMain() ) {
548 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
551 $this->getMain()->setContinuationManager( $manager );
556 /************************************************************************//**
557 * @name Parameter handling
562 * This method mangles parameter name based on the prefix supplied to the constructor.
563 * Override this method to change parameter name during runtime
564 * @param string $paramName Parameter name
565 * @return string Prefixed parameter name
567 public function encodeParamName( $paramName ) {
568 return $this->mModulePrefix
. $paramName;
572 * Using getAllowedParams(), this function makes an array of the values
573 * provided by the user, with key being the name of the variable, and
574 * value - validated value from user or default. limits will not be
575 * parsed if $parseLimit is set to false; use this when the max
576 * limit is not definitive yet, e.g. when getting revisions.
577 * @param bool $parseLimit True by default
580 public function extractRequestParams( $parseLimit = true ) {
581 // Cache parameters, for performance and to avoid bug 24564.
582 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
583 $params = $this->getFinalParams();
586 if ( $params ) { // getFinalParams() can return false
587 foreach ( $params as $paramName => $paramSettings ) {
588 $results[$paramName] = $this->getParameterFromSettings(
589 $paramName, $paramSettings, $parseLimit );
592 $this->mParamCache
[$parseLimit] = $results;
595 return $this->mParamCache
[$parseLimit];
599 * Get a value for the given parameter
600 * @param string $paramName Parameter name
601 * @param bool $parseLimit See extractRequestParams()
602 * @return mixed Parameter value
604 protected function getParameter( $paramName, $parseLimit = true ) {
605 $params = $this->getFinalParams();
606 $paramSettings = $params[$paramName];
608 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
612 * Die if none or 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 exactly one must be set
617 public function requireOnlyOneParameter( $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',
629 } elseif ( count( $intersection ) == 0 ) {
631 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
638 * Die if more than one of a certain set of parameters is set and not false.
640 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
641 * @param string $required,... Names of parameters of which at most one must be set
643 public function requireMaxOneParameter( $params, $required /*...*/ ) {
644 $required = func_get_args();
645 array_shift( $required );
646 $p = $this->getModulePrefix();
648 $intersection = array_intersect( array_keys( array_filter( $params,
649 array( $this, "parameterNotEmpty" ) ) ), $required );
651 if ( count( $intersection ) > 1 ) {
653 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
660 * Die if none of a certain set of parameters is set and not false.
663 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
664 * @param string $required,... Names of parameters of which at least one must be set
666 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
667 $required = func_get_args();
668 array_shift( $required );
669 $p = $this->getModulePrefix();
671 $intersection = array_intersect(
672 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
676 if ( count( $intersection ) == 0 ) {
677 $this->dieUsage( "At least one of the parameters {$p}" .
678 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
683 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
685 * @param object $x Parameter to check is not null/false
688 private function parameterNotEmpty( $x ) {
689 return !is_null( $x ) && $x !== false;
693 * Get a WikiPage object from a title or pageid param, if possible.
694 * Can die, if no param is set or if the title or page id is not valid.
696 * @param array $params
697 * @param bool|string $load Whether load the object's state from the database:
698 * - false: don't load (if the pageid is given, it will still be loaded)
699 * - 'fromdb': load from a slave database
700 * - 'fromdbmaster': load from the master database
703 public function getTitleOrPageId( $params, $load = false ) {
704 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
707 if ( isset( $params['title'] ) ) {
708 $titleObj = Title
::newFromText( $params['title'] );
709 if ( !$titleObj ||
$titleObj->isExternal() ) {
710 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
712 if ( !$titleObj->canExist() ) {
713 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
715 $pageObj = WikiPage
::factory( $titleObj );
716 if ( $load !== false ) {
717 $pageObj->loadPageData( $load );
719 } elseif ( isset( $params['pageid'] ) ) {
720 if ( $load === false ) {
723 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
725 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
733 * Return true if we're to watch the page, false if not, null if no change.
734 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
735 * @param Title $titleObj The page under consideration
736 * @param string $userOption The user option to consider when $watchlist=preferences.
737 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
740 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
742 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
744 switch ( $watchlist ) {
752 # If the user is already watching, don't bother checking
753 if ( $userWatching ) {
756 # If no user option was passed, use watchdefault and watchcreations
757 if ( is_null( $userOption ) ) {
758 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
759 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
762 # Watch the article based on the user preference
763 return $this->getUser()->getBoolOption( $userOption );
766 return $userWatching;
769 return $userWatching;
774 * Using the settings determine the value for the given parameter
776 * @param string $paramName Parameter name
777 * @param array|mixed $paramSettings Default value or an array of settings
778 * using PARAM_* constants.
779 * @param bool $parseLimit Parse limit?
780 * @return mixed Parameter value
782 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
783 // Some classes may decide to change parameter names
784 $encParamName = $this->encodeParamName( $paramName );
786 if ( !is_array( $paramSettings ) ) {
787 $default = $paramSettings;
789 $type = gettype( $paramSettings );
794 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
795 ?
$paramSettings[self
::PARAM_DFLT
]
797 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
798 ?
$paramSettings[self
::PARAM_ISMULTI
]
800 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
801 ?
$paramSettings[self
::PARAM_TYPE
]
803 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
804 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
806 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
807 ?
$paramSettings[self
::PARAM_DEPRECATED
]
809 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
810 ?
$paramSettings[self
::PARAM_REQUIRED
]
813 // When type is not given, and no choices, the type is the same as $default
814 if ( !isset( $type ) ) {
815 if ( isset( $default ) ) {
816 $type = gettype( $default );
818 $type = 'NULL'; // allow everything
823 if ( $type == 'boolean' ) {
824 if ( isset( $default ) && $default !== false ) {
825 // Having a default value of anything other than 'false' is not allowed
828 "Boolean param $encParamName's default is set to '$default'. " .
829 "Boolean parameters must default to false."
833 $value = $this->getMain()->getCheck( $encParamName );
834 } elseif ( $type == 'upload' ) {
835 if ( isset( $default ) ) {
836 // Having a default value is not allowed
839 "File upload param $encParamName's default is set to " .
840 "'$default'. File upload parameters may not have a default." );
843 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
845 $value = $this->getMain()->getUpload( $encParamName );
846 if ( !$value->exists() ) {
847 // This will get the value without trying to normalize it
848 // (because trying to normalize a large binary file
849 // accidentally uploaded as a field fails spectacularly)
850 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
851 if ( $value !== null ) {
853 "File upload param $encParamName is not a file upload; " .
854 "be sure to use multipart/form-data for your POST and include " .
855 "a filename in the Content-Disposition header.",
856 "badupload_{$encParamName}"
861 $value = $this->getMain()->getVal( $encParamName, $default );
863 if ( isset( $value ) && $type == 'namespace' ) {
864 $type = MWNamespace
::getValidNamespaces();
866 if ( isset( $value ) && $type == 'submodule' ) {
867 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
868 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
870 $type = $this->getModuleManager()->getNames( $paramName );
875 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
876 $value = $this->parseMultiValue(
880 is_array( $type ) ?
$type : null
884 // More validation only when choices were not given
885 // choices were validated in parseMultiValue()
886 if ( isset( $value ) ) {
887 if ( !is_array( $type ) ) {
889 case 'NULL': // nothing to do
894 if ( $required && $value === '' ) {
895 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
898 case 'integer': // Force everything using intval() and optionally validate limits
899 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
900 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
901 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
902 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
904 if ( is_array( $value ) ) {
905 $value = array_map( 'intval', $value );
906 if ( !is_null( $min ) ||
!is_null( $max ) ) {
907 foreach ( $value as &$v ) {
908 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
912 $value = intval( $value );
913 if ( !is_null( $min ) ||
!is_null( $max ) ) {
914 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
919 if ( !$parseLimit ) {
920 // Don't do any validation whatsoever
923 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
924 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
928 "MAX1 or MAX2 are not defined for the limit $encParamName"
932 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
934 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
935 if ( $value == 'max' ) {
936 $value = $this->getMain()->canApiHighLimits()
937 ?
$paramSettings[self
::PARAM_MAX2
]
938 : $paramSettings[self
::PARAM_MAX
];
939 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
941 $value = intval( $value );
942 $this->validateLimit(
946 $paramSettings[self
::PARAM_MAX
],
947 $paramSettings[self
::PARAM_MAX2
]
953 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
957 if ( is_array( $value ) ) {
958 foreach ( $value as $key => $val ) {
959 $value[$key] = $this->validateTimestamp( $val, $encParamName );
962 $value = $this->validateTimestamp( $value, $encParamName );
966 if ( is_array( $value ) ) {
967 foreach ( $value as $key => $val ) {
968 $value[$key] = $this->validateUser( $val, $encParamName );
971 $value = $this->validateUser( $value, $encParamName );
974 case 'upload': // nothing to do
977 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
981 // Throw out duplicates if requested
982 if ( !$dupes && is_array( $value ) ) {
983 $value = array_unique( $value );
986 // Set a warning if a deprecated parameter has been passed
987 if ( $deprecated && $value !== false ) {
988 $this->setWarning( "The $encParamName parameter has been deprecated." );
990 $feature = $encParamName;
992 while ( !$m->isMain() ) {
993 $p = $m->getParent();
994 $name = $m->getModuleName();
995 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
996 $feature = "{$param}={$name}&{$feature}";
999 $this->logFeatureUsage( $feature );
1001 } elseif ( $required ) {
1002 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1009 * Return an array of values that were given in a 'a|b|c' notation,
1010 * after it optionally validates them against the list allowed values.
1012 * @param string $valueName The name of the parameter (for error
1014 * @param mixed $value The value being parsed
1015 * @param bool $allowMultiple Can $value contain more than one value
1017 * @param string[]|null $allowedValues An array of values to check against. If
1018 * null, all values are accepted.
1019 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1021 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1022 if ( trim( $value ) === '' && $allowMultiple ) {
1026 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1027 // because it unstubs $wgUser
1028 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1029 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1033 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1034 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1035 "the limit is $sizeLimit" );
1038 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1039 // Bug 33482 - Allow entries with | in them for non-multiple values
1040 if ( in_array( $value, $allowedValues, true ) ) {
1044 $possibleValues = is_array( $allowedValues )
1045 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1048 "Only one $possibleValues is allowed for parameter '$valueName'",
1049 "multival_$valueName"
1053 if ( is_array( $allowedValues ) ) {
1054 // Check for unknown values
1055 $unknown = array_diff( $valuesList, $allowedValues );
1056 if ( count( $unknown ) ) {
1057 if ( $allowMultiple ) {
1058 $s = count( $unknown ) > 1 ?
's' : '';
1059 $vals = implode( ", ", $unknown );
1060 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1063 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1064 "unknown_$valueName"
1068 // Now throw them out
1069 $valuesList = array_intersect( $valuesList, $allowedValues );
1072 return $allowMultiple ?
$valuesList : $valuesList[0];
1076 * Validate the value against the minimum and user/bot maximum limits.
1077 * Prints usage info on failure.
1078 * @param string $paramName Parameter name
1079 * @param int $value Parameter value
1080 * @param int|null $min Minimum value
1081 * @param int|null $max Maximum value for users
1082 * @param int $botMax Maximum value for sysops/bots
1083 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1085 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1086 $enforceLimits = false
1088 if ( !is_null( $min ) && $value < $min ) {
1089 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1090 $this->warnOrDie( $msg, $enforceLimits );
1094 // Minimum is always validated, whereas maximum is checked only if not
1095 // running in internal call mode
1096 if ( $this->getMain()->isInternalMode() ) {
1100 // Optimization: do not check user's bot status unless really needed -- skips db query
1101 // assumes $botMax >= $max
1102 if ( !is_null( $max ) && $value > $max ) {
1103 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1104 if ( $value > $botMax ) {
1105 $msg = $this->encodeParamName( $paramName ) .
1106 " may not be over $botMax (set to $value) for bots or sysops";
1107 $this->warnOrDie( $msg, $enforceLimits );
1111 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1112 $this->warnOrDie( $msg, $enforceLimits );
1119 * Validate and normalize of parameters of type 'timestamp'
1120 * @param string $value Parameter value
1121 * @param string $encParamName Parameter name
1122 * @return string Validated and normalized parameter
1124 protected function validateTimestamp( $value, $encParamName ) {
1125 // Confusing synonyms for the current time accepted by wfTimestamp()
1126 // (wfTimestamp() also accepts various non-strings and the string of 14
1127 // ASCII NUL bytes, but those can't get here)
1129 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1131 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1132 ' If for some reason you need to explicitly specify the current time without' .
1133 ' calculating it client-side, use "now".'
1135 return wfTimestamp( TS_MW
);
1138 // Explicit synonym for the current time
1139 if ( $value === 'now' ) {
1140 return wfTimestamp( TS_MW
);
1143 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1144 if ( $unixTimestamp === false ) {
1146 "Invalid value '$value' for timestamp parameter $encParamName",
1147 "badtimestamp_{$encParamName}"
1151 return wfTimestamp( TS_MW
, $unixTimestamp );
1155 * Validate the supplied token.
1158 * @param string $token Supplied token
1159 * @param array $params All supplied parameters for the module
1161 * @throws MWException
1163 final public function validateToken( $token, array $params ) {
1164 $tokenType = $this->needsToken();
1165 $salts = ApiQueryTokens
::getTokenTypeSalts();
1166 if ( !isset( $salts[$tokenType] ) ) {
1167 throw new MWException(
1168 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1169 'without registering it'
1173 if ( $this->getUser()->matchEditToken(
1181 $webUiSalt = $this->getWebUITokenSalt( $params );
1182 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1194 * Validate and normalize of parameters of type 'user'
1195 * @param string $value Parameter value
1196 * @param string $encParamName Parameter name
1197 * @return string Validated and normalized parameter
1199 private function validateUser( $value, $encParamName ) {
1200 $title = Title
::makeTitleSafe( NS_USER
, $value );
1201 if ( $title === null ) {
1203 "Invalid value '$value' for user parameter $encParamName",
1204 "baduser_{$encParamName}"
1208 return $title->getText();
1213 /************************************************************************//**
1214 * @name Utility methods
1219 * Set a watch (or unwatch) based the based on a watchlist parameter.
1220 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1221 * @param Title $titleObj The article's title to change
1222 * @param string $userOption The user option to consider when $watch=preferences
1224 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1225 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1226 if ( $value === null ) {
1230 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1234 * Truncate an array to a certain length.
1235 * @param array $arr Array to truncate
1236 * @param int $limit Maximum length
1237 * @return bool True if the array was truncated, false otherwise
1239 public static function truncateArray( &$arr, $limit ) {
1241 while ( count( $arr ) > $limit ) {
1250 * Gets the user for whom to get the watchlist
1252 * @param array $params
1255 public function getWatchlistUser( $params ) {
1256 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1257 $user = User
::newFromName( $params['owner'], false );
1258 if ( !( $user && $user->getId() ) ) {
1259 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1261 $token = $user->getOption( 'watchlisttoken' );
1262 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1264 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1269 if ( !$this->getUser()->isLoggedIn() ) {
1270 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1272 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1273 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1275 $user = $this->getUser();
1282 * A subset of wfEscapeWikiText for BC texts
1285 * @param string|array $v
1286 * @return string|array
1288 private static function escapeWikiText( $v ) {
1289 if ( is_array( $v ) ) {
1290 return array_map( 'self::escapeWikiText', $v );
1292 return strtr( $v, array(
1293 '__' => '__', '{' => '{', '}' => '}',
1294 '[[Category:' => '[[:Category:',
1295 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1301 * Create a Message from a string or array
1303 * A string is used as a message key. An array has the message key as the
1304 * first value and message parameters as subsequent values.
1307 * @param string|array|Message $msg
1308 * @param IContextSource $context
1309 * @param array $params
1310 * @return Message|null
1312 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1313 if ( is_string( $msg ) ) {
1314 $msg = wfMessage( $msg );
1315 } elseif ( is_array( $msg ) ) {
1316 $msg = call_user_func_array( 'wfMessage', $msg );
1318 if ( !$msg instanceof Message
) {
1322 $msg->setContext( $context );
1324 $msg->params( $params );
1332 /************************************************************************//**
1333 * @name Warning and error reporting
1338 * Set warning section for this module. Users should monitor this
1339 * section to notice any changes in API. Multiple calls to this
1340 * function will result in the warning messages being separated by
1342 * @param string $warning Warning message
1344 public function setWarning( $warning ) {
1345 $msg = new ApiRawMessage( $warning, 'warning' );
1346 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1350 * Adds a warning to the output, else dies
1352 * @param string $msg Message to show as a warning, or error message if dying
1353 * @param bool $enforceLimits Whether this is an enforce (die)
1355 private function warnOrDie( $msg, $enforceLimits = false ) {
1356 if ( $enforceLimits ) {
1357 $this->dieUsage( $msg, 'integeroutofrange' );
1360 $this->setWarning( $msg );
1364 * Throw a UsageException, which will (if uncaught) call the main module's
1365 * error handler and die with an error message.
1367 * @param string $description One-line human-readable description of the
1368 * error condition, e.g., "The API requires a valid action parameter"
1369 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1370 * automated identification of the error, e.g., 'unknown_action'
1371 * @param int $httpRespCode HTTP response code
1372 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1373 * @throws UsageException always
1375 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1376 throw new UsageException(
1378 $this->encodeParamName( $errorCode ),
1385 * Get error (as code, string) from a Status object.
1388 * @param Status $status
1389 * @return array Array of code and error string
1390 * @throws MWException
1392 public function getErrorFromStatus( $status ) {
1393 if ( $status->isGood() ) {
1394 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1397 $errors = $status->getErrorsArray();
1399 // No errors? Assume the warnings should be treated as errors
1400 $errors = $status->getWarningsArray();
1403 // Still no errors? Punt
1404 $errors = array( array( 'unknownerror-nocode' ) );
1407 // Cannot use dieUsageMsg() because extensions might return custom
1409 if ( $errors[0] instanceof Message
) {
1411 $code = $msg->getKey();
1413 $code = array_shift( $errors[0] );
1414 $msg = wfMessage( $code, $errors[0] );
1416 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1417 // Translate message to code, for backwards compatibility
1418 $code = ApiBase
::$messageMap[$code]['code'];
1421 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1425 * Throw a UsageException based on the errors in the Status object.
1428 * @param Status $status
1429 * @throws UsageException always
1431 public function dieStatus( $status ) {
1432 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1433 $this->dieUsage( $msg, $code );
1436 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1438 * Array that maps message keys to error messages. $1 and friends are replaced.
1440 public static $messageMap = array(
1441 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1442 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1443 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1445 // Messages from Title::getUserPermissionsErrors()
1446 'ns-specialprotected' => array(
1447 'code' => 'unsupportednamespace',
1448 'info' => "Pages in the Special namespace can't be edited"
1450 'protectedinterface' => array(
1451 'code' => 'protectednamespace-interface',
1452 'info' => "You're not allowed to edit interface messages"
1454 'namespaceprotected' => array(
1455 'code' => 'protectednamespace',
1456 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1458 'customcssprotected' => array(
1459 'code' => 'customcssprotected',
1460 'info' => "You're not allowed to edit custom CSS pages"
1462 'customjsprotected' => array(
1463 'code' => 'customjsprotected',
1464 'info' => "You're not allowed to edit custom JavaScript pages"
1466 'cascadeprotected' => array(
1467 'code' => 'cascadeprotected',
1468 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1470 'protectedpagetext' => array(
1471 'code' => 'protectedpage',
1472 'info' => "The \"\$1\" right is required to edit this page"
1474 'protect-cantedit' => array(
1475 'code' => 'cantedit',
1476 'info' => "You can't protect this page because you can't edit it"
1478 'deleteprotected' => array(
1479 'code' => 'cantedit',
1480 'info' => "You can't delete this page because it has been protected"
1482 'badaccess-group0' => array(
1483 'code' => 'permissiondenied',
1484 'info' => "Permission denied"
1485 ), // Generic permission denied message
1486 'badaccess-groups' => array(
1487 'code' => 'permissiondenied',
1488 'info' => "Permission denied"
1490 'titleprotected' => array(
1491 'code' => 'protectedtitle',
1492 'info' => "This title has been protected from creation"
1494 'nocreate-loggedin' => array(
1495 'code' => 'cantcreate',
1496 'info' => "You don't have permission to create new pages"
1498 'nocreatetext' => array(
1499 'code' => 'cantcreate-anon',
1500 'info' => "Anonymous users can't create new pages"
1502 'movenologintext' => array(
1503 'code' => 'cantmove-anon',
1504 'info' => "Anonymous users can't move pages"
1506 'movenotallowed' => array(
1507 'code' => 'cantmove',
1508 'info' => "You don't have permission to move pages"
1510 'confirmedittext' => array(
1511 'code' => 'confirmemail',
1512 'info' => "You must confirm your email address before you can edit"
1514 'blockedtext' => array(
1515 'code' => 'blocked',
1516 'info' => "You have been blocked from editing"
1518 'autoblockedtext' => array(
1519 'code' => 'autoblocked',
1520 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1523 // Miscellaneous interface messages
1524 'actionthrottledtext' => array(
1525 'code' => 'ratelimited',
1526 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1528 'alreadyrolled' => array(
1529 'code' => 'alreadyrolled',
1530 'info' => "The page you tried to rollback was already rolled back"
1532 'cantrollback' => array(
1533 'code' => 'onlyauthor',
1534 'info' => "The page you tried to rollback only has one author"
1536 'readonlytext' => array(
1537 'code' => 'readonly',
1538 'info' => "The wiki is currently in read-only mode"
1540 'sessionfailure' => array(
1541 'code' => 'badtoken',
1542 'info' => "Invalid token" ),
1543 'cannotdelete' => array(
1544 'code' => 'cantdelete',
1545 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1547 'notanarticle' => array(
1548 'code' => 'missingtitle',
1549 'info' => "The page you requested doesn't exist"
1551 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1553 'immobile_namespace' => array(
1554 'code' => 'immobilenamespace',
1555 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1557 'articleexists' => array(
1558 'code' => 'articleexists',
1559 'info' => "The destination article already exists and is not a redirect to the source article"
1561 'protectedpage' => array(
1562 'code' => 'protectedpage',
1563 'info' => "You don't have permission to perform this move"
1565 'hookaborted' => array(
1566 'code' => 'hookaborted',
1567 'info' => "The modification you tried to make was aborted by an extension hook"
1569 'cantmove-titleprotected' => array(
1570 'code' => 'protectedtitle',
1571 'info' => "The destination article has been protected from creation"
1573 'imagenocrossnamespace' => array(
1574 'code' => 'nonfilenamespace',
1575 'info' => "Can't move a file to a non-file namespace"
1577 'imagetypemismatch' => array(
1578 'code' => 'filetypemismatch',
1579 'info' => "The new file extension doesn't match its type"
1581 // 'badarticleerror' => shouldn't happen
1582 // 'badtitletext' => shouldn't happen
1583 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1584 'range_block_disabled' => array(
1585 'code' => 'rangedisabled',
1586 'info' => "Blocking IP ranges has been disabled"
1588 'nosuchusershort' => array(
1589 'code' => 'nosuchuser',
1590 'info' => "The user you specified doesn't exist"
1592 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1593 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1594 'ipb_already_blocked' => array(
1595 'code' => 'alreadyblocked',
1596 'info' => "The user you tried to block was already blocked"
1598 'ipb_blocked_as_range' => array(
1599 'code' => 'blockedasrange',
1600 '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."
1602 'ipb_cant_unblock' => array(
1603 'code' => 'cantunblock',
1604 'info' => "The block you specified was not found. It may have been unblocked already"
1606 'mailnologin' => array(
1607 'code' => 'cantsend',
1608 '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"
1610 'ipbblocked' => array(
1611 'code' => 'ipbblocked',
1612 'info' => 'You cannot block or unblock users while you are yourself blocked'
1614 'ipbnounblockself' => array(
1615 'code' => 'ipbnounblockself',
1616 'info' => 'You are not allowed to unblock yourself'
1618 'usermaildisabled' => array(
1619 'code' => 'usermaildisabled',
1620 'info' => "User email has been disabled"
1622 'blockedemailuser' => array(
1623 'code' => 'blockedfrommail',
1624 'info' => "You have been blocked from sending email"
1626 'notarget' => array(
1627 'code' => 'notarget',
1628 'info' => "You have not specified a valid target for this action"
1631 'code' => 'noemail',
1632 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1634 'rcpatroldisabled' => array(
1635 'code' => 'patroldisabled',
1636 'info' => "Patrolling is disabled on this wiki"
1638 'markedaspatrollederror-noautopatrol' => array(
1639 'code' => 'noautopatrol',
1640 'info' => "You don't have permission to patrol your own changes"
1642 'delete-toobig' => array(
1643 'code' => 'bigdelete',
1644 'info' => "You can't delete this page because it has more than \$1 revisions"
1646 'movenotallowedfile' => array(
1647 'code' => 'cantmovefile',
1648 'info' => "You don't have permission to move files"
1650 'userrights-no-interwiki' => array(
1651 'code' => 'nointerwikiuserrights',
1652 'info' => "You don't have permission to change user rights on other wikis"
1654 'userrights-nodatabase' => array(
1655 'code' => 'nosuchdatabase',
1656 'info' => "Database \"\$1\" does not exist or is not local"
1658 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1659 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1660 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1661 'import-rootpage-invalid' => array(
1662 'code' => 'import-rootpage-invalid',
1663 'info' => 'Root page is an invalid title'
1665 'import-rootpage-nosubpage' => array(
1666 'code' => 'import-rootpage-nosubpage',
1667 'info' => 'Namespace "$1" of the root page does not allow subpages'
1670 // API-specific messages
1671 'readrequired' => array(
1672 'code' => 'readapidenied',
1673 'info' => "You need read permission to use this module"
1675 'writedisabled' => array(
1676 'code' => 'noapiwrite',
1677 '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"
1679 'writerequired' => array(
1680 'code' => 'writeapidenied',
1681 'info' => "You're not allowed to edit this wiki through the API"
1683 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1684 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1685 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1686 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1687 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1688 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1689 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1690 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1691 'create-titleexists' => array(
1692 'code' => 'create-titleexists',
1693 'info' => "Existing titles can't be protected with 'create'"
1695 'missingtitle-createonly' => array(
1696 'code' => 'missingtitle-createonly',
1697 'info' => "Missing titles can only be protected with 'create'"
1699 'cantblock' => array( 'code' => 'cantblock',
1700 'info' => "You don't have permission to block users"
1702 'canthide' => array(
1703 'code' => 'canthide',
1704 'info' => "You don't have permission to hide user names from the block log"
1706 'cantblock-email' => array(
1707 'code' => 'cantblock-email',
1708 'info' => "You don't have permission to block users from sending email through the wiki"
1710 'unblock-notarget' => array(
1711 'code' => 'notarget',
1712 'info' => "Either the id or the user parameter must be set"
1714 'unblock-idanduser' => array(
1715 'code' => 'idanduser',
1716 'info' => "The id and user parameters can't be used together"
1718 'cantunblock' => array(
1719 'code' => 'permissiondenied',
1720 'info' => "You don't have permission to unblock users"
1722 'cannotundelete' => array(
1723 'code' => 'cantundelete',
1724 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1726 'permdenied-undelete' => array(
1727 'code' => 'permissiondenied',
1728 'info' => "You don't have permission to restore deleted revisions"
1730 'createonly-exists' => array(
1731 'code' => 'articleexists',
1732 'info' => "The article you tried to create has been created already"
1734 'nocreate-missing' => array(
1735 'code' => 'missingtitle',
1736 'info' => "The article you tried to edit doesn't exist"
1738 'cantchangecontentmodel' => array(
1739 'code' => 'cantchangecontentmodel',
1740 'info' => "You don't have permission to change the content model of a page"
1742 'nosuchrcid' => array(
1743 'code' => 'nosuchrcid',
1744 'info' => "There is no change with rcid \"\$1\""
1746 'nosuchlogid' => array(
1747 'code' => 'nosuchlogid',
1748 'info' => "There is no log entry with ID \"\$1\""
1750 'protect-invalidaction' => array(
1751 'code' => 'protect-invalidaction',
1752 'info' => "Invalid protection type \"\$1\""
1754 'protect-invalidlevel' => array(
1755 'code' => 'protect-invalidlevel',
1756 'info' => "Invalid protection level \"\$1\""
1758 'toofewexpiries' => array(
1759 'code' => 'toofewexpiries',
1760 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1762 'cantimport' => array(
1763 'code' => 'cantimport',
1764 'info' => "You don't have permission to import pages"
1766 'cantimport-upload' => array(
1767 'code' => 'cantimport-upload',
1768 'info' => "You don't have permission to import uploaded pages"
1770 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1771 'importuploaderrorsize' => array(
1772 'code' => 'filetoobig',
1773 'info' => 'The file you uploaded is bigger than the maximum upload size'
1775 'importuploaderrorpartial' => array(
1776 'code' => 'partialupload',
1777 'info' => 'The file was only partially uploaded'
1779 'importuploaderrortemp' => array(
1780 'code' => 'notempdir',
1781 'info' => 'The temporary upload directory is missing'
1783 'importcantopen' => array(
1784 'code' => 'cantopenfile',
1785 'info' => "Couldn't open the uploaded file"
1787 'import-noarticle' => array(
1788 'code' => 'badinterwiki',
1789 'info' => 'Invalid interwiki title specified'
1791 'importbadinterwiki' => array(
1792 'code' => 'badinterwiki',
1793 'info' => 'Invalid interwiki title specified'
1795 'import-unknownerror' => array(
1796 'code' => 'import-unknownerror',
1797 'info' => "Unknown error on import: \"\$1\""
1799 'cantoverwrite-sharedfile' => array(
1800 'code' => 'cantoverwrite-sharedfile',
1801 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1803 'sharedfile-exists' => array(
1804 'code' => 'fileexists-sharedrepo-perm',
1805 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1807 'mustbeposted' => array(
1808 'code' => 'mustbeposted',
1809 'info' => "The \$1 module requires a POST request"
1813 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1815 'specialpage-cantexecute' => array(
1816 'code' => 'specialpage-cantexecute',
1817 'info' => "You don't have permission to view the results of this special page"
1819 'invalidoldimage' => array(
1820 'code' => 'invalidoldimage',
1821 'info' => 'The oldimage parameter has invalid format'
1823 'nodeleteablefile' => array(
1824 'code' => 'nodeleteablefile',
1825 'info' => 'No such old version of the file'
1827 'fileexists-forbidden' => array(
1828 'code' => 'fileexists-forbidden',
1829 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1831 'fileexists-shared-forbidden' => array(
1832 'code' => 'fileexists-shared-forbidden',
1833 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1835 'filerevert-badversion' => array(
1836 'code' => 'filerevert-badversion',
1837 'info' => 'There is no previous local version of this file with the provided timestamp.'
1840 // ApiEditPage messages
1841 'noimageredirect-anon' => array(
1842 'code' => 'noimageredirect-anon',
1843 'info' => "Anonymous users can't create image redirects"
1845 'noimageredirect-logged' => array(
1846 'code' => 'noimageredirect',
1847 'info' => "You don't have permission to create image redirects"
1849 'spamdetected' => array(
1850 'code' => 'spamdetected',
1851 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1853 'contenttoobig' => array(
1854 'code' => 'contenttoobig',
1855 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1857 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1858 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1859 'wasdeleted' => array(
1860 'code' => 'pagedeleted',
1861 'info' => "The page has been deleted since you fetched its timestamp"
1863 'blankpage' => array(
1864 'code' => 'emptypage',
1865 'info' => "Creating new, empty pages is not allowed"
1867 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1868 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1869 'missingtext' => array(
1871 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1873 'emptynewsection' => array(
1874 'code' => 'emptynewsection',
1875 'info' => 'Creating empty new sections is not possible.'
1877 'revwrongpage' => array(
1878 'code' => 'revwrongpage',
1879 'info' => "r\$1 is not a revision of \"\$2\""
1881 'undo-failure' => array(
1882 'code' => 'undofailure',
1883 'info' => 'Undo failed due to conflicting intermediate edits'
1885 'content-not-allowed-here' => array(
1886 'code' => 'contentnotallowedhere',
1887 'info' => 'Content model "$1" is not allowed at title "$2"'
1890 // Messages from WikiPage::doEit()
1891 'edit-hook-aborted' => array(
1892 'code' => 'edit-hook-aborted',
1893 'info' => "Your edit was aborted by an ArticleSave hook"
1895 'edit-gone-missing' => array(
1896 'code' => 'edit-gone-missing',
1897 'info' => "The page you tried to edit doesn't seem to exist anymore"
1899 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1900 'edit-already-exists' => array(
1901 'code' => 'edit-already-exists',
1902 'info' => 'It seems the page you tried to create already exist'
1906 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1907 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1908 'uploaddisabled' => array(
1909 'code' => 'uploaddisabled',
1910 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1912 'copyuploaddisabled' => array(
1913 'code' => 'copyuploaddisabled',
1914 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1916 'copyuploadbaddomain' => array(
1917 'code' => 'copyuploadbaddomain',
1918 'info' => 'Uploads by URL are not allowed from this domain.'
1920 'copyuploadbadurl' => array(
1921 'code' => 'copyuploadbadurl',
1922 'info' => 'Upload not allowed from this URL.'
1925 'filename-tooshort' => array(
1926 'code' => 'filename-tooshort',
1927 'info' => 'The filename is too short'
1929 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1930 'illegal-filename' => array(
1931 'code' => 'illegal-filename',
1932 'info' => 'The filename is not allowed'
1934 'filetype-missing' => array(
1935 'code' => 'filetype-missing',
1936 'info' => 'The file is missing an extension'
1939 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1941 // @codingStandardsIgnoreEnd
1944 * Helper function for readonly errors
1946 * @throws UsageException always
1948 public function dieReadOnly() {
1949 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1950 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1951 array( 'readonlyreason' => wfReadOnlyReason() ) );
1955 * Output the error message related to a certain array
1956 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1957 * @throws UsageException always
1959 public function dieUsageMsg( $error ) {
1960 # most of the time we send a 1 element, so we might as well send it as
1961 # a string and make this an array here.
1962 if ( is_string( $error ) ) {
1963 $error = array( $error );
1965 $parsed = $this->parseMsg( $error );
1966 $this->dieUsage( $parsed['info'], $parsed['code'] );
1970 * Will only set a warning instead of failing if the global $wgDebugAPI
1971 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1972 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1973 * @throws UsageException
1976 public function dieUsageMsgOrDebug( $error ) {
1977 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1978 $this->dieUsageMsg( $error );
1981 if ( is_string( $error ) ) {
1982 $error = array( $error );
1984 $parsed = $this->parseMsg( $error );
1985 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1989 * Die with the $prefix.'badcontinue' error. This call is common enough to
1990 * make it into the base method.
1991 * @param bool $condition Will only die if this value is true
1992 * @throws UsageException
1995 protected function dieContinueUsageIf( $condition ) {
1998 'Invalid continue param. You should pass the original value returned by the previous query',
2004 * Return the error message related to a certain array
2005 * @param array $error Element of a getUserPermissionsErrors()-style array
2006 * @return array('code' => code, 'info' => info)
2008 public function parseMsg( $error ) {
2009 $error = (array)$error; // It seems strings sometimes make their way in here
2010 $key = array_shift( $error );
2012 // Check whether the error array was nested
2013 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2014 if ( is_array( $key ) ) {
2016 $key = array_shift( $error );
2019 if ( isset( self
::$messageMap[$key] ) ) {
2021 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
2022 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2026 // If the key isn't present, throw an "unknown error"
2027 return $this->parseMsg( array( 'unknownerror', $key ) );
2031 * Internal code errors should be reported with this method
2032 * @param string $method Method or function name
2033 * @param string $message Error message
2034 * @throws MWException always
2036 protected static function dieDebug( $method, $message ) {
2037 throw new MWException( "Internal error in $method: $message" );
2041 * Write logging information for API features to a debug log, for usage
2043 * @param string $feature Feature being used.
2045 protected function logFeatureUsage( $feature ) {
2046 $request = $this->getRequest();
2047 $s = '"' . addslashes( $feature ) . '"' .
2048 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2049 ' "' . $request->getIP() . '"' .
2050 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2051 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2052 wfDebugLog( 'api-feature-usage', $s, 'private' );
2057 /************************************************************************//**
2058 * @name Help message generation
2063 * Return the description message.
2065 * @return string|array|Message
2067 protected function getDescriptionMessage() {
2068 return "apihelp-{$this->getModulePath()}-description";
2072 * Get final module description, after hooks have had a chance to tweak it as
2075 * @since 1.25, returns Message[] rather than string[]
2078 public function getFinalDescription() {
2079 $desc = $this->getDescription();
2080 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2081 $desc = self
::escapeWikiText( $desc );
2082 if ( is_array( $desc ) ) {
2083 $desc = join( "\n", $desc );
2085 $desc = (string)$desc;
2088 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2089 $this->getModulePrefix(),
2090 $this->getModuleName(),
2091 $this->getModulePath(),
2093 if ( !$msg->exists() ) {
2094 $msg = $this->msg( 'api-help-fallback-description', $desc );
2096 $msgs = array( $msg );
2098 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2104 * Get final list of parameters, after hooks have had a chance to
2105 * tweak it as needed.
2107 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2108 * @return array|bool False on no parameters
2109 * @since 1.21 $flags param added
2111 public function getFinalParams( $flags = 0 ) {
2112 $params = $this->getAllowedParams( $flags );
2117 if ( $this->needsToken() ) {
2118 $params['token'] = array(
2119 ApiBase
::PARAM_TYPE
=> 'string',
2120 ApiBase
::PARAM_REQUIRED
=> true,
2121 ApiBase
::PARAM_HELP_MSG
=> array(
2122 'api-help-param-token',
2123 $this->needsToken(),
2125 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2128 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2134 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2137 * @since 1.25, returns array of Message[] rather than array of string[]
2138 * @return array Keys are parameter names, values are arrays of Message objects
2140 public function getFinalParamDescription() {
2141 $prefix = $this->getModulePrefix();
2142 $name = $this->getModuleName();
2143 $path = $this->getModulePath();
2145 $desc = $this->getParamDescription();
2146 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2151 $desc = self
::escapeWikiText( $desc );
2153 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2155 foreach ( $params as $param => $settings ) {
2156 if ( !is_array( $settings ) ) {
2157 $settings = array();
2160 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2161 if ( is_array( $d ) ) {
2162 // Special handling for prop parameters
2163 $d = array_map( function ( $line ) {
2164 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2165 $line = "\n;{$m[1]}:{$m[2]}";
2169 $d = join( ' ', $d );
2172 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2173 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2175 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2176 if ( !$msg->exists() ) {
2177 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2180 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2181 array( $prefix, $param, $name, $path ) );
2183 $this->dieDebug( __METHOD__
,
2184 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2186 $msgs[$param] = array( $msg );
2188 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2189 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2190 $this->dieDebug( __METHOD__
,
2191 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2193 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2194 $this->dieDebug( __METHOD__
,
2195 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2196 'ApiBase::PARAM_TYPE is an array' );
2199 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2200 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2201 if ( isset( $valueMsgs[$value] ) ) {
2202 $msg = $valueMsgs[$value];
2204 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2206 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2207 array( $prefix, $param, $name, $path, $value ) );
2209 $m = new ApiHelpParamValueMessage(
2211 array( $m->getKey(), 'api-help-param-no-description' ),
2214 $msgs[$param][] = $m->setContext( $this->getContext() );
2216 $this->dieDebug( __METHOD__
,
2217 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2222 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2223 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2224 $this->dieDebug( __METHOD__
,
2225 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2227 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2228 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2229 array( $prefix, $param, $name, $path ) );
2231 $msgs[$param][] = $m;
2233 $this->dieDebug( __METHOD__
,
2234 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2240 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2246 * Generates the list of flags for the help screen and for action=paraminfo
2248 * Corresponding messages: api-help-flag-deprecated,
2249 * api-help-flag-internal, api-help-flag-readrights,
2250 * api-help-flag-writerights, api-help-flag-mustbeposted
2254 protected function getHelpFlags() {
2257 if ( $this->isDeprecated() ) {
2258 $flags[] = 'deprecated';
2260 if ( $this->isInternal() ) {
2261 $flags[] = 'internal';
2263 if ( $this->isReadMode() ) {
2264 $flags[] = 'readrights';
2266 if ( $this->isWriteMode() ) {
2267 $flags[] = 'writerights';
2269 if ( $this->mustBePosted() ) {
2270 $flags[] = 'mustbeposted';
2277 * Returns information about the source of this module, if known
2279 * Returned array is an array with the following keys:
2280 * - path: Install path
2281 * - name: Extension name, or "MediaWiki" for core
2282 * - namemsg: (optional) i18n message key for a display name
2283 * - license-name: (optional) Name of license
2285 * @return array|null
2287 protected function getModuleSourceInfo() {
2290 if ( $this->mModuleSource
!== false ) {
2291 return $this->mModuleSource
;
2294 // First, try to find where the module comes from...
2295 $rClass = new ReflectionClass( $this );
2296 $path = $rClass->getFileName();
2299 $this->mModuleSource
= null;
2302 $path = realpath( $path ) ?
: $path;
2304 // Build map of extension directories to extension info
2305 if ( self
::$extensionInfo === null ) {
2306 self
::$extensionInfo = array(
2307 realpath( __DIR__
) ?
: __DIR__
=> array(
2309 'name' => 'MediaWiki',
2310 'license-name' => 'GPL-2.0+',
2312 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2318 'license-name' => null,
2320 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2321 foreach ( $group as $ext ) {
2322 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2323 // This shouldn't happen, but does anyway.
2327 $extpath = $ext['path'];
2328 if ( !is_dir( $extpath ) ) {
2329 $extpath = dirname( $extpath );
2331 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2332 array_intersect_key( $ext, $keep );
2335 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2336 $extpath = $ext['path'];
2337 if ( !is_dir( $extpath ) ) {
2338 $extpath = dirname( $extpath );
2340 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2341 array_intersect_key( $ext, $keep );
2345 // Now traverse parent directories until we find a match or run out of
2348 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2350 $this->mModuleSource
= self
::$extensionInfo[$path];
2351 return $this->mModuleSource
;
2355 $path = dirname( $path );
2356 } while ( $path !== $oldpath );
2358 // No idea what extension this might be.
2359 $this->mModuleSource
= null;
2364 * Called from ApiHelp before the pieces are joined together and returned.
2366 * This exists mainly for ApiMain to add the Permissions and Credits
2367 * sections. Other modules probably don't need it.
2369 * @param string[] &$help Array of help data
2370 * @param array $options Options passed to ApiHelp::getHelp
2371 * @param array &$tocData If a TOC is being generated, this array has keys
2372 * as anchors in the page and values as for Linker::generateTOC().
2374 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2379 /************************************************************************//**
2384 /// @deprecated since 1.24
2385 const PROP_ROOT
= 'ROOT';
2386 /// @deprecated since 1.24
2387 const PROP_LIST
= 'LIST';
2388 /// @deprecated since 1.24
2389 const PROP_TYPE
= 0;
2390 /// @deprecated since 1.24
2391 const PROP_NULLABLE
= 1;
2394 * Formerly returned a string that identifies the version of the extending
2395 * class. Typically included the class name, the svn revision, timestamp,
2396 * and last author. Usually done with SVN's Id keyword
2398 * @deprecated since 1.21, version string is no longer supported
2401 public function getVersion() {
2402 wfDeprecated( __METHOD__
, '1.21' );
2407 * Formerly used to fetch a list of possible properites in the result,
2408 * somehow organized with respect to the prop parameter that causes them to
2409 * be returned. The specific semantics of the return value was never
2410 * specified. Since this was never possible to be accurately updated, it
2413 * @deprecated since 1.24
2414 * @return array|bool
2416 protected function getResultProperties() {
2417 wfDeprecated( __METHOD__
, '1.24' );
2422 * @see self::getResultProperties()
2423 * @deprecated since 1.24
2424 * @return array|bool
2426 public function getFinalResultProperties() {
2427 wfDeprecated( __METHOD__
, '1.24' );
2432 * @see self::getResultProperties()
2433 * @deprecated since 1.24
2435 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2436 wfDeprecated( __METHOD__
, '1.24' );
2440 * @see self::getPossibleErrors()
2441 * @deprecated since 1.24
2444 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2445 wfDeprecated( __METHOD__
, '1.24' );
2450 * @see self::getPossibleErrors()
2451 * @deprecated since 1.24
2454 public function getRequireMaxOneParameterErrorMessages( $params ) {
2455 wfDeprecated( __METHOD__
, '1.24' );
2460 * @see self::getPossibleErrors()
2461 * @deprecated since 1.24
2464 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2465 wfDeprecated( __METHOD__
, '1.24' );
2470 * @see self::getPossibleErrors()
2471 * @deprecated since 1.24
2474 public function getTitleOrPageIdErrorMessage() {
2475 wfDeprecated( __METHOD__
, '1.24' );
2480 * This formerly attempted to return a list of all possible errors returned
2481 * by the module. However, this was impossible to maintain in many cases
2482 * since errors could come from other areas of MediaWiki and in some cases
2483 * from arbitrary extension hooks. Since a partial list claiming to be
2484 * comprehensive is unlikely to be useful, it was removed.
2486 * @deprecated since 1.24
2489 public function getPossibleErrors() {
2490 wfDeprecated( __METHOD__
, '1.24' );
2495 * @see self::getPossibleErrors()
2496 * @deprecated since 1.24
2499 public function getFinalPossibleErrors() {
2500 wfDeprecated( __METHOD__
, '1.24' );
2505 * @see self::getPossibleErrors()
2506 * @deprecated since 1.24
2509 public function parseErrors( $errors ) {
2510 wfDeprecated( __METHOD__
, '1.24' );
2515 * Returns the description string for this module
2517 * Ignored if an i18n message exists for
2518 * "apihelp-{$this->getModulePath()}-description".
2520 * @deprecated since 1.25
2521 * @return Message|string|array
2523 protected function getDescription() {
2528 * Returns an array of parameter descriptions.
2530 * For each parameter, ignored if an i18n message exists for the parameter.
2531 * By default that message is
2532 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2533 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2534 * self::getFinalParams().
2536 * @deprecated since 1.25
2537 * @return array|bool False on no parameter descriptions
2539 protected function getParamDescription() {
2544 * Returns usage examples for this module.
2546 * Return value as an array is either:
2547 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2549 * - sequential numeric keys with even-numbered keys being display-text
2550 * and odd-numbered keys being partial urls
2551 * - partial URLs as keys with display-text (string or array-to-be-joined)
2553 * Return value as a string is the same as an array with a numeric key and
2554 * that value, and boolean false means "no examples".
2556 * @deprecated since 1.25, use getExamplesMessages() instead
2557 * @return bool|string|array
2559 protected function getExamples() {
2564 * Generates help message for this module, or false if there is no description
2565 * @deprecated since 1.25
2566 * @return string|bool
2568 public function makeHelpMsg() {
2569 wfDeprecated( __METHOD__
, '1.25' );
2570 static $lnPrfx = "\n ";
2572 $msg = $this->getFinalDescription();
2574 if ( $msg !== false ) {
2576 if ( !is_array( $msg ) ) {
2581 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2583 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2585 if ( $this->isReadMode() ) {
2586 $msg .= "\nThis module requires read rights";
2588 if ( $this->isWriteMode() ) {
2589 $msg .= "\nThis module requires write rights";
2591 if ( $this->mustBePosted() ) {
2592 $msg .= "\nThis module only accepts POST requests";
2594 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2595 $this->mustBePosted()
2601 $paramsMsg = $this->makeHelpMsgParameters();
2602 if ( $paramsMsg !== false ) {
2603 $msg .= "Parameters:\n$paramsMsg";
2606 $examples = $this->getExamples();
2608 if ( !is_array( $examples ) ) {
2613 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2614 foreach ( $examples as $k => $v ) {
2615 if ( is_numeric( $k ) ) {
2618 if ( is_array( $v ) ) {
2619 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2621 $msgExample = " $v";
2624 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2634 * @deprecated since 1.25
2635 * @param string $item
2638 private function indentExampleText( $item ) {
2643 * @deprecated since 1.25
2644 * @param string $prefix Text to split output items
2645 * @param string $title What is being output
2646 * @param string|array $input
2649 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2650 wfDeprecated( __METHOD__
, '1.25' );
2651 if ( $input === false ) {
2654 if ( !is_array( $input ) ) {
2655 $input = array( $input );
2658 if ( count( $input ) > 0 ) {
2660 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2664 $msg .= implode( $prefix, $input ) . "\n";
2673 * Generates the parameter descriptions for this module, to be displayed in the
2675 * @deprecated since 1.25
2676 * @return string|bool
2678 public function makeHelpMsgParameters() {
2679 wfDeprecated( __METHOD__
, '1.25' );
2680 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2682 $paramsDescription = $this->getFinalParamDescription();
2684 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2685 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2686 foreach ( $params as $paramName => $paramSettings ) {
2687 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2688 if ( is_array( $desc ) ) {
2689 $desc = implode( $paramPrefix, $desc );
2693 if ( !is_array( $paramSettings ) ) {
2694 $paramSettings = array(
2695 self
::PARAM_DFLT
=> $paramSettings,
2699 // handle missing type
2700 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2701 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2702 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2704 if ( is_bool( $dflt ) ) {
2705 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2706 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2707 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2708 } elseif ( is_int( $dflt ) ) {
2709 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2713 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2714 && $paramSettings[self
::PARAM_DEPRECATED
]
2716 $desc = "DEPRECATED! $desc";
2719 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2720 && $paramSettings[self
::PARAM_REQUIRED
]
2722 $desc .= $paramPrefix . "This parameter is required";
2725 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2726 ?
$paramSettings[self
::PARAM_TYPE
]
2728 if ( isset( $type ) ) {
2729 $hintPipeSeparated = true;
2730 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2731 ?
$paramSettings[self
::PARAM_ISMULTI
]
2734 $prompt = 'Values (separate with \'|\'): ';
2736 $prompt = 'One value: ';
2739 if ( $type === 'submodule' ) {
2740 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2741 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2743 $type = $this->getModuleManager()->getNames( $paramName );
2747 if ( is_array( $type ) ) {
2749 $nothingPrompt = '';
2750 foreach ( $type as $t ) {
2752 $nothingPrompt = 'Can be empty, or ';
2757 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2758 $choicesstring = implode( ', ', $choices );
2759 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2760 $hintPipeSeparated = false;
2764 // Special handling because namespaces are
2765 // type-limited, yet they are not given
2766 $desc .= $paramPrefix . $prompt;
2767 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2768 100, $descWordwrap );
2769 $hintPipeSeparated = false;
2772 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2773 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2774 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2776 $desc .= ' allowed';
2779 $s = $multi ?
's' : '';
2780 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2781 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2782 if ( $hasMin ||
$hasMax ) {
2784 $intRangeStr = "The value$s must be no less than " .
2785 "{$paramSettings[self::PARAM_MIN]}";
2786 } elseif ( !$hasMin ) {
2787 $intRangeStr = "The value$s must be no more than " .
2788 "{$paramSettings[self::PARAM_MAX]}";
2790 $intRangeStr = "The value$s must be between " .
2791 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2794 $desc .= $paramPrefix . $intRangeStr;
2798 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2804 if ( $hintPipeSeparated ) {
2805 $desc .= $paramPrefix . "Separate values with '|'";
2808 $isArray = is_array( $type );
2810 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2812 $desc .= $paramPrefix . "Maximum number of values " .
2813 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2818 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2819 if ( !is_null( $default ) && $default !== false ) {
2820 $desc .= $paramPrefix . "Default: $default";
2823 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2833 * @deprecated since 1.25, always returns empty string
2834 * @param IDatabase|bool $db
2837 public function getModuleProfileName( $db = false ) {
2838 wfDeprecated( __METHOD__
, '1.25' );
2843 * @deprecated since 1.25
2845 public function profileIn() {
2846 // No wfDeprecated() yet because extensions call this and might need to
2847 // keep doing so for BC.
2851 * @deprecated since 1.25
2853 public function profileOut() {
2854 // No wfDeprecated() yet because extensions call this and might need to
2855 // keep doing so for BC.
2859 * @deprecated since 1.25
2861 public function safeProfileOut() {
2862 wfDeprecated( __METHOD__
, '1.25' );
2866 * @deprecated since 1.25, always returns 0
2869 public function getProfileTime() {
2870 wfDeprecated( __METHOD__
, '1.25' );
2875 * @deprecated since 1.25
2877 public function profileDBIn() {
2878 wfDeprecated( __METHOD__
, '1.25' );
2882 * @deprecated since 1.25
2884 public function profileDBOut() {
2885 wfDeprecated( __METHOD__
, '1.25' );
2889 * @deprecated since 1.25, always returns 0
2892 public function getProfileDBTime() {
2893 wfDeprecated( __METHOD__
, '1.25' );
2898 * Get the result data array (read-only)
2899 * @deprecated since 1.25, use $this->getResult() methods instead
2902 public function getResultData() {
2903 wfDeprecated( __METHOD__
, '1.25' );
2904 return $this->getResult()->getData();
2908 * Call wfTransactionalTimeLimit() if this request was POSTed
2911 protected function useTransactionalTimeLimit() {
2912 if ( $this->getRequest()->wasPosted() ) {
2913 wfTransactionalTimeLimit();
2921 * For really cool vim folding this needs to be at the end:
2922 * vim: foldmarker=@{,@} foldmethod=marker