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 ) {
349 * Returns data for HTTP conditional request mechanisms.
352 * @param string $condition Condition being queried:
353 * - last-modified: Return a timestamp representing the maximum of the
354 * last-modified dates for all resources involved in the request. See
355 * RFC 7232 § 2.2 for semantics.
356 * - etag: Return an entity-tag representing the state of all resources involved
357 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
358 * @return string|boolean|null As described above, or null if no value is available.
360 public function getConditionalRequestData( $condition ) {
366 /************************************************************************//**
367 * @name Data access methods
372 * Get the name of the module being executed by this instance
375 public function getModuleName() {
376 return $this->mModuleName
;
380 * Get parameter prefix (usually two letters or an empty string).
383 public function getModulePrefix() {
384 return $this->mModulePrefix
;
388 * Get the main module
391 public function getMain() {
392 return $this->mMainModule
;
396 * Returns true if this module is the main module ($this === $this->mMainModule),
400 public function isMain() {
401 return $this === $this->mMainModule
;
405 * Get the parent of this module
407 * @return ApiBase|null
409 public function getParent() {
410 return $this->isMain() ?
null : $this->getMain();
414 * Returns true if the current request breaks the same-origin policy.
416 * For example, json with callbacks.
418 * https://en.wikipedia.org/wiki/Same-origin_policy
423 public function lacksSameOriginSecurity() {
424 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
428 * Get the path to this module
433 public function getModulePath() {
434 if ( $this->isMain() ) {
436 } elseif ( $this->getParent()->isMain() ) {
437 return $this->getModuleName();
439 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
444 * Get a module from its module path
447 * @param string $path
448 * @return ApiBase|null
449 * @throws UsageException
451 public function getModuleFromPath( $path ) {
452 $module = $this->getMain();
453 if ( $path === 'main' ) {
457 $parts = explode( '+', $path );
458 if ( count( $parts ) === 1 ) {
459 // In case the '+' was typed into URL, it resolves as a space
460 $parts = explode( ' ', $path );
463 $count = count( $parts );
464 for ( $i = 0; $i < $count; $i++
) {
466 $manager = $parent->getModuleManager();
467 if ( $manager === null ) {
468 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
469 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
471 $module = $manager->getModule( $parts[$i] );
473 if ( $module === null ) {
474 $errorPath = $i ?
join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
476 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
486 * Get the result object
489 public function getResult() {
490 // Main module has getResult() method overridden
491 // Safety - avoid infinite loop:
492 if ( $this->isMain() ) {
493 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
496 return $this->getMain()->getResult();
500 * Get the error formatter
501 * @return ApiErrorFormatter
503 public function getErrorFormatter() {
504 // Main module has getErrorFormatter() method overridden
505 // Safety - avoid infinite loop:
506 if ( $this->isMain() ) {
507 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
510 return $this->getMain()->getErrorFormatter();
514 * Gets a default slave database connection object
515 * @return DatabaseBase
517 protected function getDB() {
518 if ( !isset( $this->mSlaveDB
) ) {
519 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
522 return $this->mSlaveDB
;
526 * Get the continuation manager
527 * @return ApiContinuationManager|null
529 public function getContinuationManager() {
530 // Main module has getContinuationManager() method overridden
531 // Safety - avoid infinite loop:
532 if ( $this->isMain() ) {
533 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
536 return $this->getMain()->getContinuationManager();
540 * Set the continuation manager
541 * @param ApiContinuationManager|null
543 public function setContinuationManager( $manager ) {
544 // Main module has setContinuationManager() method overridden
545 // Safety - avoid infinite loop:
546 if ( $this->isMain() ) {
547 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
550 $this->getMain()->setContinuationManager( $manager );
555 /************************************************************************//**
556 * @name Parameter handling
561 * This method mangles parameter name based on the prefix supplied to the constructor.
562 * Override this method to change parameter name during runtime
563 * @param string $paramName Parameter name
564 * @return string Prefixed parameter name
566 public function encodeParamName( $paramName ) {
567 return $this->mModulePrefix
. $paramName;
571 * Using getAllowedParams(), this function makes an array of the values
572 * provided by the user, with key being the name of the variable, and
573 * value - validated value from user or default. limits will not be
574 * parsed if $parseLimit is set to false; use this when the max
575 * limit is not definitive yet, e.g. when getting revisions.
576 * @param bool $parseLimit True by default
579 public function extractRequestParams( $parseLimit = true ) {
580 // Cache parameters, for performance and to avoid bug 24564.
581 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
582 $params = $this->getFinalParams();
585 if ( $params ) { // getFinalParams() can return false
586 foreach ( $params as $paramName => $paramSettings ) {
587 $results[$paramName] = $this->getParameterFromSettings(
588 $paramName, $paramSettings, $parseLimit );
591 $this->mParamCache
[$parseLimit] = $results;
594 return $this->mParamCache
[$parseLimit];
598 * Get a value for the given parameter
599 * @param string $paramName Parameter name
600 * @param bool $parseLimit See extractRequestParams()
601 * @return mixed Parameter value
603 protected function getParameter( $paramName, $parseLimit = true ) {
604 $params = $this->getFinalParams();
605 $paramSettings = $params[$paramName];
607 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
611 * Die if none or more than one of a certain set of parameters is set and not false.
613 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
614 * @param string $required,... Names of parameters of which exactly one must be set
616 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
617 $required = func_get_args();
618 array_shift( $required );
619 $p = $this->getModulePrefix();
621 $intersection = array_intersect( array_keys( array_filter( $params,
622 array( $this, "parameterNotEmpty" ) ) ), $required );
624 if ( count( $intersection ) > 1 ) {
626 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
628 } elseif ( count( $intersection ) == 0 ) {
630 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
637 * Die if more than one of a certain set of parameters is set and not false.
639 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
640 * @param string $required,... Names of parameters of which at most one must be set
642 public function requireMaxOneParameter( $params, $required /*...*/ ) {
643 $required = func_get_args();
644 array_shift( $required );
645 $p = $this->getModulePrefix();
647 $intersection = array_intersect( array_keys( array_filter( $params,
648 array( $this, "parameterNotEmpty" ) ) ), $required );
650 if ( count( $intersection ) > 1 ) {
652 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
659 * Die if none of a certain set of parameters is set and not false.
662 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
663 * @param string $required,... Names of parameters of which at least one must be set
665 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
666 $required = func_get_args();
667 array_shift( $required );
668 $p = $this->getModulePrefix();
670 $intersection = array_intersect(
671 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
675 if ( count( $intersection ) == 0 ) {
676 $this->dieUsage( "At least one of the parameters {$p}" .
677 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
682 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
684 * @param object $x Parameter to check is not null/false
687 private function parameterNotEmpty( $x ) {
688 return !is_null( $x ) && $x !== false;
692 * Get a WikiPage object from a title or pageid param, if possible.
693 * Can die, if no param is set or if the title or page id is not valid.
695 * @param array $params
696 * @param bool|string $load Whether load the object's state from the database:
697 * - false: don't load (if the pageid is given, it will still be loaded)
698 * - 'fromdb': load from a slave database
699 * - 'fromdbmaster': load from the master database
702 public function getTitleOrPageId( $params, $load = false ) {
703 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
706 if ( isset( $params['title'] ) ) {
707 $titleObj = Title
::newFromText( $params['title'] );
708 if ( !$titleObj ||
$titleObj->isExternal() ) {
709 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
711 if ( !$titleObj->canExist() ) {
712 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
714 $pageObj = WikiPage
::factory( $titleObj );
715 if ( $load !== false ) {
716 $pageObj->loadPageData( $load );
718 } elseif ( isset( $params['pageid'] ) ) {
719 if ( $load === false ) {
722 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
724 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
732 * Return true if we're to watch the page, false if not, null if no change.
733 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
734 * @param Title $titleObj The page under consideration
735 * @param string $userOption The user option to consider when $watchlist=preferences.
736 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
739 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
741 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
743 switch ( $watchlist ) {
751 # If the user is already watching, don't bother checking
752 if ( $userWatching ) {
755 # If no user option was passed, use watchdefault and watchcreations
756 if ( is_null( $userOption ) ) {
757 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
758 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
761 # Watch the article based on the user preference
762 return $this->getUser()->getBoolOption( $userOption );
765 return $userWatching;
768 return $userWatching;
773 * Using the settings determine the value for the given parameter
775 * @param string $paramName Parameter name
776 * @param array|mixed $paramSettings Default value or an array of settings
777 * using PARAM_* constants.
778 * @param bool $parseLimit Parse limit?
779 * @return mixed Parameter value
781 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
782 // Some classes may decide to change parameter names
783 $encParamName = $this->encodeParamName( $paramName );
785 if ( !is_array( $paramSettings ) ) {
786 $default = $paramSettings;
788 $type = gettype( $paramSettings );
793 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
794 ?
$paramSettings[self
::PARAM_DFLT
]
796 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
797 ?
$paramSettings[self
::PARAM_ISMULTI
]
799 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
800 ?
$paramSettings[self
::PARAM_TYPE
]
802 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
803 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
805 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
806 ?
$paramSettings[self
::PARAM_DEPRECATED
]
808 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
809 ?
$paramSettings[self
::PARAM_REQUIRED
]
812 // When type is not given, and no choices, the type is the same as $default
813 if ( !isset( $type ) ) {
814 if ( isset( $default ) ) {
815 $type = gettype( $default );
817 $type = 'NULL'; // allow everything
822 if ( $type == 'boolean' ) {
823 if ( isset( $default ) && $default !== false ) {
824 // Having a default value of anything other than 'false' is not allowed
827 "Boolean param $encParamName's default is set to '$default'. " .
828 "Boolean parameters must default to false."
832 $value = $this->getMain()->getCheck( $encParamName );
833 } elseif ( $type == 'upload' ) {
834 if ( isset( $default ) ) {
835 // Having a default value is not allowed
838 "File upload param $encParamName's default is set to " .
839 "'$default'. File upload parameters may not have a default." );
842 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
844 $value = $this->getMain()->getUpload( $encParamName );
845 if ( !$value->exists() ) {
846 // This will get the value without trying to normalize it
847 // (because trying to normalize a large binary file
848 // accidentally uploaded as a field fails spectacularly)
849 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
850 if ( $value !== null ) {
852 "File upload param $encParamName is not a file upload; " .
853 "be sure to use multipart/form-data for your POST and include " .
854 "a filename in the Content-Disposition header.",
855 "badupload_{$encParamName}"
860 $value = $this->getMain()->getVal( $encParamName, $default );
862 if ( isset( $value ) && $type == 'namespace' ) {
863 $type = MWNamespace
::getValidNamespaces();
865 if ( isset( $value ) && $type == 'submodule' ) {
866 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
867 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
869 $type = $this->getModuleManager()->getNames( $paramName );
874 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
875 $value = $this->parseMultiValue(
879 is_array( $type ) ?
$type : null
883 // More validation only when choices were not given
884 // choices were validated in parseMultiValue()
885 if ( isset( $value ) ) {
886 if ( !is_array( $type ) ) {
888 case 'NULL': // nothing to do
893 if ( $required && $value === '' ) {
894 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
897 case 'integer': // Force everything using intval() and optionally validate limits
898 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
899 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
900 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
901 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
903 if ( is_array( $value ) ) {
904 $value = array_map( 'intval', $value );
905 if ( !is_null( $min ) ||
!is_null( $max ) ) {
906 foreach ( $value as &$v ) {
907 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
911 $value = intval( $value );
912 if ( !is_null( $min ) ||
!is_null( $max ) ) {
913 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
918 if ( !$parseLimit ) {
919 // Don't do any validation whatsoever
922 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
923 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
927 "MAX1 or MAX2 are not defined for the limit $encParamName"
931 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
933 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
934 if ( $value == 'max' ) {
935 $value = $this->getMain()->canApiHighLimits()
936 ?
$paramSettings[self
::PARAM_MAX2
]
937 : $paramSettings[self
::PARAM_MAX
];
938 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
940 $value = intval( $value );
941 $this->validateLimit(
945 $paramSettings[self
::PARAM_MAX
],
946 $paramSettings[self
::PARAM_MAX2
]
952 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
956 if ( is_array( $value ) ) {
957 foreach ( $value as $key => $val ) {
958 $value[$key] = $this->validateTimestamp( $val, $encParamName );
961 $value = $this->validateTimestamp( $value, $encParamName );
965 if ( is_array( $value ) ) {
966 foreach ( $value as $key => $val ) {
967 $value[$key] = $this->validateUser( $val, $encParamName );
970 $value = $this->validateUser( $value, $encParamName );
973 case 'upload': // nothing to do
976 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
980 // Throw out duplicates if requested
981 if ( !$dupes && is_array( $value ) ) {
982 $value = array_unique( $value );
985 // Set a warning if a deprecated parameter has been passed
986 if ( $deprecated && $value !== false ) {
987 $this->setWarning( "The $encParamName parameter has been deprecated." );
989 } elseif ( $required ) {
990 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
997 * Return an array of values that were given in a 'a|b|c' notation,
998 * after it optionally validates them against the list allowed values.
1000 * @param string $valueName The name of the parameter (for error
1002 * @param mixed $value The value being parsed
1003 * @param bool $allowMultiple Can $value contain more than one value
1005 * @param string[]|null $allowedValues An array of values to check against. If
1006 * null, all values are accepted.
1007 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1009 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1010 if ( trim( $value ) === '' && $allowMultiple ) {
1014 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1015 // because it unstubs $wgUser
1016 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1017 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1021 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1022 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1023 "the limit is $sizeLimit" );
1026 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1027 // Bug 33482 - Allow entries with | in them for non-multiple values
1028 if ( in_array( $value, $allowedValues, true ) ) {
1032 $possibleValues = is_array( $allowedValues )
1033 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1036 "Only one $possibleValues is allowed for parameter '$valueName'",
1037 "multival_$valueName"
1041 if ( is_array( $allowedValues ) ) {
1042 // Check for unknown values
1043 $unknown = array_diff( $valuesList, $allowedValues );
1044 if ( count( $unknown ) ) {
1045 if ( $allowMultiple ) {
1046 $s = count( $unknown ) > 1 ?
's' : '';
1047 $vals = implode( ", ", $unknown );
1048 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1051 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1052 "unknown_$valueName"
1056 // Now throw them out
1057 $valuesList = array_intersect( $valuesList, $allowedValues );
1060 return $allowMultiple ?
$valuesList : $valuesList[0];
1064 * Validate the value against the minimum and user/bot maximum limits.
1065 * Prints usage info on failure.
1066 * @param string $paramName Parameter name
1067 * @param int $value Parameter value
1068 * @param int|null $min Minimum value
1069 * @param int|null $max Maximum value for users
1070 * @param int $botMax Maximum value for sysops/bots
1071 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1073 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1074 if ( !is_null( $min ) && $value < $min ) {
1075 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1076 $this->warnOrDie( $msg, $enforceLimits );
1080 // Minimum is always validated, whereas maximum is checked only if not
1081 // running in internal call mode
1082 if ( $this->getMain()->isInternalMode() ) {
1086 // Optimization: do not check user's bot status unless really needed -- skips db query
1087 // assumes $botMax >= $max
1088 if ( !is_null( $max ) && $value > $max ) {
1089 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1090 if ( $value > $botMax ) {
1091 $msg = $this->encodeParamName( $paramName ) .
1092 " may not be over $botMax (set to $value) for bots or sysops";
1093 $this->warnOrDie( $msg, $enforceLimits );
1097 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1098 $this->warnOrDie( $msg, $enforceLimits );
1105 * Validate and normalize of parameters of type 'timestamp'
1106 * @param string $value Parameter value
1107 * @param string $encParamName Parameter name
1108 * @return string Validated and normalized parameter
1110 protected function validateTimestamp( $value, $encParamName ) {
1111 // Confusing synonyms for the current time accepted by wfTimestamp()
1112 // (wfTimestamp() also accepts various non-strings and the string of 14
1113 // ASCII NUL bytes, but those can't get here)
1115 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1117 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1118 ' If for some reason you need to explicitly specify the current time without' .
1119 ' calculating it client-side, use "now".'
1121 return wfTimestamp( TS_MW
);
1124 // Explicit synonym for the current time
1125 if ( $value === 'now' ) {
1126 return wfTimestamp( TS_MW
);
1129 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1130 if ( $unixTimestamp === false ) {
1132 "Invalid value '$value' for timestamp parameter $encParamName",
1133 "badtimestamp_{$encParamName}"
1137 return wfTimestamp( TS_MW
, $unixTimestamp );
1141 * Validate the supplied token.
1144 * @param string $token Supplied token
1145 * @param array $params All supplied parameters for the module
1147 * @throws MWException
1149 final public function validateToken( $token, array $params ) {
1150 $tokenType = $this->needsToken();
1151 $salts = ApiQueryTokens
::getTokenTypeSalts();
1152 if ( !isset( $salts[$tokenType] ) ) {
1153 throw new MWException(
1154 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1155 'without registering it'
1159 if ( $this->getUser()->matchEditToken(
1167 $webUiSalt = $this->getWebUITokenSalt( $params );
1168 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1180 * Validate and normalize of parameters of type 'user'
1181 * @param string $value Parameter value
1182 * @param string $encParamName Parameter name
1183 * @return string Validated and normalized parameter
1185 private function validateUser( $value, $encParamName ) {
1186 $title = Title
::makeTitleSafe( NS_USER
, $value );
1187 if ( $title === null ) {
1189 "Invalid value '$value' for user parameter $encParamName",
1190 "baduser_{$encParamName}"
1194 return $title->getText();
1199 /************************************************************************//**
1200 * @name Utility methods
1205 * Set a watch (or unwatch) based the based on a watchlist parameter.
1206 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1207 * @param Title $titleObj The article's title to change
1208 * @param string $userOption The user option to consider when $watch=preferences
1210 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1211 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1212 if ( $value === null ) {
1216 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1220 * Truncate an array to a certain length.
1221 * @param array $arr Array to truncate
1222 * @param int $limit Maximum length
1223 * @return bool True if the array was truncated, false otherwise
1225 public static function truncateArray( &$arr, $limit ) {
1227 while ( count( $arr ) > $limit ) {
1236 * Gets the user for whom to get the watchlist
1238 * @param array $params
1241 public function getWatchlistUser( $params ) {
1242 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1243 $user = User
::newFromName( $params['owner'], false );
1244 if ( !( $user && $user->getId() ) ) {
1245 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1247 $token = $user->getOption( 'watchlisttoken' );
1248 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1250 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1255 if ( !$this->getUser()->isLoggedIn() ) {
1256 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1258 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1259 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1261 $user = $this->getUser();
1268 * A subset of wfEscapeWikiText for BC texts
1271 * @param string|array $v
1272 * @return string|array
1274 private static function escapeWikiText( $v ) {
1275 if ( is_array( $v ) ) {
1276 return array_map( 'self::escapeWikiText', $v );
1278 return strtr( $v, array(
1279 '__' => '__', '{' => '{', '}' => '}',
1280 '[[Category:' => '[[:Category:',
1281 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1287 * Create a Message from a string or array
1289 * A string is used as a message key. An array has the message key as the
1290 * first value and message parameters as subsequent values.
1293 * @param string|array|Message $msg
1294 * @param IContextSource $context
1295 * @param array $params
1296 * @return Message|null
1298 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1299 if ( is_string( $msg ) ) {
1300 $msg = wfMessage( $msg );
1301 } elseif ( is_array( $msg ) ) {
1302 $msg = call_user_func_array( 'wfMessage', $msg );
1304 if ( !$msg instanceof Message
) {
1308 $msg->setContext( $context );
1310 $msg->params( $params );
1318 /************************************************************************//**
1319 * @name Warning and error reporting
1324 * Set warning section for this module. Users should monitor this
1325 * section to notice any changes in API. Multiple calls to this
1326 * function will result in the warning messages being separated by
1328 * @param string $warning Warning message
1330 public function setWarning( $warning ) {
1331 $msg = new ApiRawMessage( $warning, 'warning' );
1332 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1336 * Adds a warning to the output, else dies
1338 * @param string $msg Message to show as a warning, or error message if dying
1339 * @param bool $enforceLimits Whether this is an enforce (die)
1341 private function warnOrDie( $msg, $enforceLimits = false ) {
1342 if ( $enforceLimits ) {
1343 $this->dieUsage( $msg, 'integeroutofrange' );
1346 $this->setWarning( $msg );
1350 * Throw a UsageException, which will (if uncaught) call the main module's
1351 * error handler and die with an error message.
1353 * @param string $description One-line human-readable description of the
1354 * error condition, e.g., "The API requires a valid action parameter"
1355 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1356 * automated identification of the error, e.g., 'unknown_action'
1357 * @param int $httpRespCode HTTP response code
1358 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1359 * @throws UsageException
1361 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1362 throw new UsageException(
1364 $this->encodeParamName( $errorCode ),
1371 * Get error (as code, string) from a Status object.
1374 * @param Status $status
1375 * @return array Array of code and error string
1376 * @throws MWException
1378 public function getErrorFromStatus( $status ) {
1379 if ( $status->isGood() ) {
1380 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1383 $errors = $status->getErrorsArray();
1385 // No errors? Assume the warnings should be treated as errors
1386 $errors = $status->getWarningsArray();
1389 // Still no errors? Punt
1390 $errors = array( array( 'unknownerror-nocode' ) );
1393 // Cannot use dieUsageMsg() because extensions might return custom
1395 if ( $errors[0] instanceof Message
) {
1397 $code = $msg->getKey();
1399 $code = array_shift( $errors[0] );
1400 $msg = wfMessage( $code, $errors[0] );
1402 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1403 // Translate message to code, for backwards compatibility
1404 $code = ApiBase
::$messageMap[$code]['code'];
1407 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1411 * Throw a UsageException based on the errors in the Status object.
1414 * @param Status $status
1415 * @throws MWException
1417 public function dieStatus( $status ) {
1419 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1420 $this->dieUsage( $msg, $code );
1423 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1425 * Array that maps message keys to error messages. $1 and friends are replaced.
1427 public static $messageMap = array(
1428 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1429 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1430 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1432 // Messages from Title::getUserPermissionsErrors()
1433 'ns-specialprotected' => array(
1434 'code' => 'unsupportednamespace',
1435 'info' => "Pages in the Special namespace can't be edited"
1437 'protectedinterface' => array(
1438 'code' => 'protectednamespace-interface',
1439 'info' => "You're not allowed to edit interface messages"
1441 'namespaceprotected' => array(
1442 'code' => 'protectednamespace',
1443 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1445 'customcssprotected' => array(
1446 'code' => 'customcssprotected',
1447 'info' => "You're not allowed to edit custom CSS pages"
1449 'customjsprotected' => array(
1450 'code' => 'customjsprotected',
1451 'info' => "You're not allowed to edit custom JavaScript pages"
1453 'cascadeprotected' => array(
1454 'code' => 'cascadeprotected',
1455 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1457 'protectedpagetext' => array(
1458 'code' => 'protectedpage',
1459 'info' => "The \"\$1\" right is required to edit this page"
1461 'protect-cantedit' => array(
1462 'code' => 'cantedit',
1463 'info' => "You can't protect this page because you can't edit it"
1465 'deleteprotected' => array(
1466 'code' => 'cantedit',
1467 'info' => "You can't delete this page because it has been protected"
1469 'badaccess-group0' => array(
1470 'code' => 'permissiondenied',
1471 'info' => "Permission denied"
1472 ), // Generic permission denied message
1473 'badaccess-groups' => array(
1474 'code' => 'permissiondenied',
1475 'info' => "Permission denied"
1477 'titleprotected' => array(
1478 'code' => 'protectedtitle',
1479 'info' => "This title has been protected from creation"
1481 'nocreate-loggedin' => array(
1482 'code' => 'cantcreate',
1483 'info' => "You don't have permission to create new pages"
1485 'nocreatetext' => array(
1486 'code' => 'cantcreate-anon',
1487 'info' => "Anonymous users can't create new pages"
1489 'movenologintext' => array(
1490 'code' => 'cantmove-anon',
1491 'info' => "Anonymous users can't move pages"
1493 'movenotallowed' => array(
1494 'code' => 'cantmove',
1495 'info' => "You don't have permission to move pages"
1497 'confirmedittext' => array(
1498 'code' => 'confirmemail',
1499 'info' => "You must confirm your email address before you can edit"
1501 'blockedtext' => array(
1502 'code' => 'blocked',
1503 'info' => "You have been blocked from editing"
1505 'autoblockedtext' => array(
1506 'code' => 'autoblocked',
1507 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1510 // Miscellaneous interface messages
1511 'actionthrottledtext' => array(
1512 'code' => 'ratelimited',
1513 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1515 'alreadyrolled' => array(
1516 'code' => 'alreadyrolled',
1517 'info' => "The page you tried to rollback was already rolled back"
1519 'cantrollback' => array(
1520 'code' => 'onlyauthor',
1521 'info' => "The page you tried to rollback only has one author"
1523 'readonlytext' => array(
1524 'code' => 'readonly',
1525 'info' => "The wiki is currently in read-only mode"
1527 'sessionfailure' => array(
1528 'code' => 'badtoken',
1529 'info' => "Invalid token" ),
1530 'cannotdelete' => array(
1531 'code' => 'cantdelete',
1532 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1534 'notanarticle' => array(
1535 'code' => 'missingtitle',
1536 'info' => "The page you requested doesn't exist"
1538 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1540 'immobile_namespace' => array(
1541 'code' => 'immobilenamespace',
1542 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1544 'articleexists' => array(
1545 'code' => 'articleexists',
1546 'info' => "The destination article already exists and is not a redirect to the source article"
1548 'protectedpage' => array(
1549 'code' => 'protectedpage',
1550 'info' => "You don't have permission to perform this move"
1552 'hookaborted' => array(
1553 'code' => 'hookaborted',
1554 'info' => "The modification you tried to make was aborted by an extension hook"
1556 'cantmove-titleprotected' => array(
1557 'code' => 'protectedtitle',
1558 'info' => "The destination article has been protected from creation"
1560 'imagenocrossnamespace' => array(
1561 'code' => 'nonfilenamespace',
1562 'info' => "Can't move a file to a non-file namespace"
1564 'imagetypemismatch' => array(
1565 'code' => 'filetypemismatch',
1566 'info' => "The new file extension doesn't match its type"
1568 // 'badarticleerror' => shouldn't happen
1569 // 'badtitletext' => shouldn't happen
1570 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1571 'range_block_disabled' => array(
1572 'code' => 'rangedisabled',
1573 'info' => "Blocking IP ranges has been disabled"
1575 'nosuchusershort' => array(
1576 'code' => 'nosuchuser',
1577 'info' => "The user you specified doesn't exist"
1579 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1580 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1581 'ipb_already_blocked' => array(
1582 'code' => 'alreadyblocked',
1583 'info' => "The user you tried to block was already blocked"
1585 'ipb_blocked_as_range' => array(
1586 'code' => 'blockedasrange',
1587 '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."
1589 'ipb_cant_unblock' => array(
1590 'code' => 'cantunblock',
1591 'info' => "The block you specified was not found. It may have been unblocked already"
1593 'mailnologin' => array(
1594 'code' => 'cantsend',
1595 '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"
1597 'ipbblocked' => array(
1598 'code' => 'ipbblocked',
1599 'info' => 'You cannot block or unblock users while you are yourself blocked'
1601 'ipbnounblockself' => array(
1602 'code' => 'ipbnounblockself',
1603 'info' => 'You are not allowed to unblock yourself'
1605 'usermaildisabled' => array(
1606 'code' => 'usermaildisabled',
1607 'info' => "User email has been disabled"
1609 'blockedemailuser' => array(
1610 'code' => 'blockedfrommail',
1611 'info' => "You have been blocked from sending email"
1613 'notarget' => array(
1614 'code' => 'notarget',
1615 'info' => "You have not specified a valid target for this action"
1618 'code' => 'noemail',
1619 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1621 'rcpatroldisabled' => array(
1622 'code' => 'patroldisabled',
1623 'info' => "Patrolling is disabled on this wiki"
1625 'markedaspatrollederror-noautopatrol' => array(
1626 'code' => 'noautopatrol',
1627 'info' => "You don't have permission to patrol your own changes"
1629 'delete-toobig' => array(
1630 'code' => 'bigdelete',
1631 'info' => "You can't delete this page because it has more than \$1 revisions"
1633 'movenotallowedfile' => array(
1634 'code' => 'cantmovefile',
1635 'info' => "You don't have permission to move files"
1637 'userrights-no-interwiki' => array(
1638 'code' => 'nointerwikiuserrights',
1639 'info' => "You don't have permission to change user rights on other wikis"
1641 'userrights-nodatabase' => array(
1642 'code' => 'nosuchdatabase',
1643 'info' => "Database \"\$1\" does not exist or is not local"
1645 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1646 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1647 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1648 'import-rootpage-invalid' => array(
1649 'code' => 'import-rootpage-invalid',
1650 'info' => 'Root page is an invalid title'
1652 'import-rootpage-nosubpage' => array(
1653 'code' => 'import-rootpage-nosubpage',
1654 'info' => 'Namespace "$1" of the root page does not allow subpages'
1657 // API-specific messages
1658 'readrequired' => array(
1659 'code' => 'readapidenied',
1660 'info' => "You need read permission to use this module"
1662 'writedisabled' => array(
1663 'code' => 'noapiwrite',
1664 '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"
1666 'writerequired' => array(
1667 'code' => 'writeapidenied',
1668 'info' => "You're not allowed to edit this wiki through the API"
1670 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1671 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1672 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1673 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1674 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1675 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1676 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1677 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1678 'create-titleexists' => array(
1679 'code' => 'create-titleexists',
1680 'info' => "Existing titles can't be protected with 'create'"
1682 'missingtitle-createonly' => array(
1683 'code' => 'missingtitle-createonly',
1684 'info' => "Missing titles can only be protected with 'create'"
1686 'cantblock' => array( 'code' => 'cantblock',
1687 'info' => "You don't have permission to block users"
1689 'canthide' => array(
1690 'code' => 'canthide',
1691 'info' => "You don't have permission to hide user names from the block log"
1693 'cantblock-email' => array(
1694 'code' => 'cantblock-email',
1695 'info' => "You don't have permission to block users from sending email through the wiki"
1697 'unblock-notarget' => array(
1698 'code' => 'notarget',
1699 'info' => "Either the id or the user parameter must be set"
1701 'unblock-idanduser' => array(
1702 'code' => 'idanduser',
1703 'info' => "The id and user parameters can't be used together"
1705 'cantunblock' => array(
1706 'code' => 'permissiondenied',
1707 'info' => "You don't have permission to unblock users"
1709 'cannotundelete' => array(
1710 'code' => 'cantundelete',
1711 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1713 'permdenied-undelete' => array(
1714 'code' => 'permissiondenied',
1715 'info' => "You don't have permission to restore deleted revisions"
1717 'createonly-exists' => array(
1718 'code' => 'articleexists',
1719 'info' => "The article you tried to create has been created already"
1721 'nocreate-missing' => array(
1722 'code' => 'missingtitle',
1723 'info' => "The article you tried to edit doesn't exist"
1725 'cantchangecontentmodel' => array(
1726 'code' => 'cantchangecontentmodel',
1727 'info' => "You don't have permission to change the content model of a page"
1729 'nosuchrcid' => array(
1730 'code' => 'nosuchrcid',
1731 'info' => "There is no change with rcid \"\$1\""
1733 'nosuchlogid' => array(
1734 'code' => 'nosuchlogid',
1735 'info' => "There is no log entry with ID \"\$1\""
1737 'protect-invalidaction' => array(
1738 'code' => 'protect-invalidaction',
1739 'info' => "Invalid protection type \"\$1\""
1741 'protect-invalidlevel' => array(
1742 'code' => 'protect-invalidlevel',
1743 'info' => "Invalid protection level \"\$1\""
1745 'toofewexpiries' => array(
1746 'code' => 'toofewexpiries',
1747 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1749 'cantimport' => array(
1750 'code' => 'cantimport',
1751 'info' => "You don't have permission to import pages"
1753 'cantimport-upload' => array(
1754 'code' => 'cantimport-upload',
1755 'info' => "You don't have permission to import uploaded pages"
1757 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1758 'importuploaderrorsize' => array(
1759 'code' => 'filetoobig',
1760 'info' => 'The file you uploaded is bigger than the maximum upload size'
1762 'importuploaderrorpartial' => array(
1763 'code' => 'partialupload',
1764 'info' => 'The file was only partially uploaded'
1766 'importuploaderrortemp' => array(
1767 'code' => 'notempdir',
1768 'info' => 'The temporary upload directory is missing'
1770 'importcantopen' => array(
1771 'code' => 'cantopenfile',
1772 'info' => "Couldn't open the uploaded file"
1774 'import-noarticle' => array(
1775 'code' => 'badinterwiki',
1776 'info' => 'Invalid interwiki title specified'
1778 'importbadinterwiki' => array(
1779 'code' => 'badinterwiki',
1780 'info' => 'Invalid interwiki title specified'
1782 'import-unknownerror' => array(
1783 'code' => 'import-unknownerror',
1784 'info' => "Unknown error on import: \"\$1\""
1786 'cantoverwrite-sharedfile' => array(
1787 'code' => 'cantoverwrite-sharedfile',
1788 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1790 'sharedfile-exists' => array(
1791 'code' => 'fileexists-sharedrepo-perm',
1792 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1794 'mustbeposted' => array(
1795 'code' => 'mustbeposted',
1796 'info' => "The \$1 module requires a POST request"
1800 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1802 'specialpage-cantexecute' => array(
1803 'code' => 'specialpage-cantexecute',
1804 'info' => "You don't have permission to view the results of this special page"
1806 'invalidoldimage' => array(
1807 'code' => 'invalidoldimage',
1808 'info' => 'The oldimage parameter has invalid format'
1810 'nodeleteablefile' => array(
1811 'code' => 'nodeleteablefile',
1812 'info' => 'No such old version of the file'
1814 'fileexists-forbidden' => array(
1815 'code' => 'fileexists-forbidden',
1816 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1818 'fileexists-shared-forbidden' => array(
1819 'code' => 'fileexists-shared-forbidden',
1820 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1822 'filerevert-badversion' => array(
1823 'code' => 'filerevert-badversion',
1824 'info' => 'There is no previous local version of this file with the provided timestamp.'
1827 // ApiEditPage messages
1828 'noimageredirect-anon' => array(
1829 'code' => 'noimageredirect-anon',
1830 'info' => "Anonymous users can't create image redirects"
1832 'noimageredirect-logged' => array(
1833 'code' => 'noimageredirect',
1834 'info' => "You don't have permission to create image redirects"
1836 'spamdetected' => array(
1837 'code' => 'spamdetected',
1838 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1840 'contenttoobig' => array(
1841 'code' => 'contenttoobig',
1842 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1844 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1845 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1846 'wasdeleted' => array(
1847 'code' => 'pagedeleted',
1848 'info' => "The page has been deleted since you fetched its timestamp"
1850 'blankpage' => array(
1851 'code' => 'emptypage',
1852 'info' => "Creating new, empty pages is not allowed"
1854 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1855 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1856 'missingtext' => array(
1858 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1860 'emptynewsection' => array(
1861 'code' => 'emptynewsection',
1862 'info' => 'Creating empty new sections is not possible.'
1864 'revwrongpage' => array(
1865 'code' => 'revwrongpage',
1866 'info' => "r\$1 is not a revision of \"\$2\""
1868 'undo-failure' => array(
1869 'code' => 'undofailure',
1870 'info' => 'Undo failed due to conflicting intermediate edits'
1872 'content-not-allowed-here' => array(
1873 'code' => 'contentnotallowedhere',
1874 'info' => 'Content model "$1" is not allowed at title "$2"'
1877 // Messages from WikiPage::doEit()
1878 'edit-hook-aborted' => array(
1879 'code' => 'edit-hook-aborted',
1880 'info' => "Your edit was aborted by an ArticleSave hook"
1882 'edit-gone-missing' => array(
1883 'code' => 'edit-gone-missing',
1884 'info' => "The page you tried to edit doesn't seem to exist anymore"
1886 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1887 'edit-already-exists' => array(
1888 'code' => 'edit-already-exists',
1889 'info' => 'It seems the page you tried to create already exist'
1893 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1894 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1895 'uploaddisabled' => array(
1896 'code' => 'uploaddisabled',
1897 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1899 'copyuploaddisabled' => array(
1900 'code' => 'copyuploaddisabled',
1901 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1903 'copyuploadbaddomain' => array(
1904 'code' => 'copyuploadbaddomain',
1905 'info' => 'Uploads by URL are not allowed from this domain.'
1907 'copyuploadbadurl' => array(
1908 'code' => 'copyuploadbadurl',
1909 'info' => 'Upload not allowed from this URL.'
1912 'filename-tooshort' => array(
1913 'code' => 'filename-tooshort',
1914 'info' => 'The filename is too short'
1916 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1917 'illegal-filename' => array(
1918 'code' => 'illegal-filename',
1919 'info' => 'The filename is not allowed'
1921 'filetype-missing' => array(
1922 'code' => 'filetype-missing',
1923 'info' => 'The file is missing an extension'
1926 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1928 // @codingStandardsIgnoreEnd
1931 * Helper function for readonly errors
1933 public function dieReadOnly() {
1934 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1935 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1936 array( 'readonlyreason' => wfReadOnlyReason() ) );
1940 * Output the error message related to a certain array
1941 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1943 public function dieUsageMsg( $error ) {
1944 # most of the time we send a 1 element, so we might as well send it as
1945 # a string and make this an array here.
1946 if ( is_string( $error ) ) {
1947 $error = array( $error );
1949 $parsed = $this->parseMsg( $error );
1950 $this->dieUsage( $parsed['info'], $parsed['code'] );
1954 * Will only set a warning instead of failing if the global $wgDebugAPI
1955 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1956 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1959 public function dieUsageMsgOrDebug( $error ) {
1960 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1961 $this->dieUsageMsg( $error );
1964 if ( is_string( $error ) ) {
1965 $error = array( $error );
1967 $parsed = $this->parseMsg( $error );
1968 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1972 * Die with the $prefix.'badcontinue' error. This call is common enough to
1973 * make it into the base method.
1974 * @param bool $condition Will only die if this value is true
1977 protected function dieContinueUsageIf( $condition ) {
1980 'Invalid continue param. You should pass the original value returned by the previous query',
1986 * Return the error message related to a certain array
1987 * @param array $error Element of a getUserPermissionsErrors()-style array
1988 * @return array('code' => code, 'info' => info)
1990 public function parseMsg( $error ) {
1991 $error = (array)$error; // It seems strings sometimes make their way in here
1992 $key = array_shift( $error );
1994 // Check whether the error array was nested
1995 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1996 if ( is_array( $key ) ) {
1998 $key = array_shift( $error );
2001 if ( isset( self
::$messageMap[$key] ) ) {
2003 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
2004 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2008 // If the key isn't present, throw an "unknown error"
2009 return $this->parseMsg( array( 'unknownerror', $key ) );
2013 * Internal code errors should be reported with this method
2014 * @param string $method Method or function name
2015 * @param string $message Error message
2016 * @throws MWException
2018 protected static function dieDebug( $method, $message ) {
2019 throw new MWException( "Internal error in $method: $message" );
2023 * Write logging information for API features to a debug log, for usage
2025 * @param string $feature Feature being used.
2027 protected function logFeatureUsage( $feature ) {
2028 $request = $this->getRequest();
2029 $s = '"' . addslashes( $feature ) . '"' .
2030 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2031 ' "' . $request->getIP() . '"' .
2032 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2033 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2034 wfDebugLog( 'api-feature-usage', $s, 'private' );
2039 /************************************************************************//**
2040 * @name Help message generation
2045 * Return the description message.
2047 * @return string|array|Message
2049 protected function getDescriptionMessage() {
2050 return "apihelp-{$this->getModulePath()}-description";
2054 * Get final module description, after hooks have had a chance to tweak it as
2057 * @since 1.25, returns Message[] rather than string[]
2060 public function getFinalDescription() {
2061 $desc = $this->getDescription();
2062 Hooks
::run( 'APIGetDescription', array( &$this, &$desc ) );
2063 $desc = self
::escapeWikiText( $desc );
2064 if ( is_array( $desc ) ) {
2065 $desc = join( "\n", $desc );
2067 $desc = (string)$desc;
2070 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2071 $this->getModulePrefix(),
2072 $this->getModuleName(),
2073 $this->getModulePath(),
2075 if ( !$msg->exists() ) {
2076 $msg = $this->msg( 'api-help-fallback-description', $desc );
2078 $msgs = array( $msg );
2080 Hooks
::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2086 * Get final list of parameters, after hooks have had a chance to
2087 * tweak it as needed.
2089 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2090 * @return array|bool False on no parameters
2091 * @since 1.21 $flags param added
2093 public function getFinalParams( $flags = 0 ) {
2094 $params = $this->getAllowedParams( $flags );
2099 if ( $this->needsToken() ) {
2100 $params['token'] = array(
2101 ApiBase
::PARAM_TYPE
=> 'string',
2102 ApiBase
::PARAM_REQUIRED
=> true,
2103 ApiBase
::PARAM_HELP_MSG
=> array(
2104 'api-help-param-token',
2105 $this->needsToken(),
2107 ) +
( isset( $params['token'] ) ?
$params['token'] : array() );
2110 Hooks
::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2116 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2119 * @since 1.25, returns array of Message[] rather than array of string[]
2120 * @return array Keys are parameter names, values are arrays of Message objects
2122 public function getFinalParamDescription() {
2123 $prefix = $this->getModulePrefix();
2124 $name = $this->getModuleName();
2125 $path = $this->getModulePath();
2127 $desc = $this->getParamDescription();
2128 Hooks
::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2133 $desc = self
::escapeWikiText( $desc );
2135 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2137 foreach ( $params as $param => $settings ) {
2138 if ( !is_array( $settings ) ) {
2139 $settings = array();
2142 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2143 if ( is_array( $d ) ) {
2144 // Special handling for prop parameters
2145 $d = array_map( function ( $line ) {
2146 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2147 $line = "\n;{$m[1]}:{$m[2]}";
2151 $d = join( ' ', $d );
2154 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2155 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2157 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2158 if ( !$msg->exists() ) {
2159 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2162 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2163 array( $prefix, $param, $name, $path ) );
2165 $this->dieDebug( __METHOD__
,
2166 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2168 $msgs[$param] = array( $msg );
2170 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2171 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2172 $this->dieDebug( __METHOD__
,
2173 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2175 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2176 $this->dieDebug( __METHOD__
,
2177 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2178 'ApiBase::PARAM_TYPE is an array' );
2181 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2182 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2183 if ( isset( $valueMsgs[$value] ) ) {
2184 $msg = $valueMsgs[$value];
2186 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2188 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2189 array( $prefix, $param, $name, $path, $value ) );
2191 $m = new ApiHelpParamValueMessage(
2193 array( $m->getKey(), 'api-help-param-no-description' ),
2196 $msgs[$param][] = $m->setContext( $this->getContext() );
2198 $this->dieDebug( __METHOD__
,
2199 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2204 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2205 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2206 $this->dieDebug( __METHOD__
,
2207 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2209 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2210 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2211 array( $prefix, $param, $name, $path ) );
2213 $msgs[$param][] = $m;
2215 $this->dieDebug( __METHOD__
,
2216 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2222 Hooks
::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2228 * Generates the list of flags for the help screen and for action=paraminfo
2230 * Corresponding messages: api-help-flag-deprecated,
2231 * api-help-flag-internal, api-help-flag-readrights,
2232 * api-help-flag-writerights, api-help-flag-mustbeposted
2236 protected function getHelpFlags() {
2239 if ( $this->isDeprecated() ) {
2240 $flags[] = 'deprecated';
2242 if ( $this->isInternal() ) {
2243 $flags[] = 'internal';
2245 if ( $this->isReadMode() ) {
2246 $flags[] = 'readrights';
2248 if ( $this->isWriteMode() ) {
2249 $flags[] = 'writerights';
2251 if ( $this->mustBePosted() ) {
2252 $flags[] = 'mustbeposted';
2259 * Returns information about the source of this module, if known
2261 * Returned array is an array with the following keys:
2262 * - path: Install path
2263 * - name: Extension name, or "MediaWiki" for core
2264 * - namemsg: (optional) i18n message key for a display name
2265 * - license-name: (optional) Name of license
2267 * @return array|null
2269 protected function getModuleSourceInfo() {
2272 if ( $this->mModuleSource
!== false ) {
2273 return $this->mModuleSource
;
2276 // First, try to find where the module comes from...
2277 $rClass = new ReflectionClass( $this );
2278 $path = $rClass->getFileName();
2281 $this->mModuleSource
= null;
2284 $path = realpath( $path ) ?
: $path;
2286 // Build map of extension directories to extension info
2287 if ( self
::$extensionInfo === null ) {
2288 self
::$extensionInfo = array(
2289 realpath( __DIR__
) ?
: __DIR__
=> array(
2291 'name' => 'MediaWiki',
2292 'license-name' => 'GPL-2.0+',
2294 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2300 'license-name' => null,
2302 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2303 foreach ( $group as $ext ) {
2304 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2305 // This shouldn't happen, but does anyway.
2309 $extpath = $ext['path'];
2310 if ( !is_dir( $extpath ) ) {
2311 $extpath = dirname( $extpath );
2313 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2314 array_intersect_key( $ext, $keep );
2317 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2318 $extpath = $ext['path'];
2319 if ( !is_dir( $extpath ) ) {
2320 $extpath = dirname( $extpath );
2322 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2323 array_intersect_key( $ext, $keep );
2327 // Now traverse parent directories until we find a match or run out of
2330 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2332 $this->mModuleSource
= self
::$extensionInfo[$path];
2333 return $this->mModuleSource
;
2337 $path = dirname( $path );
2338 } while ( $path !== $oldpath );
2340 // No idea what extension this might be.
2341 $this->mModuleSource
= null;
2346 * Called from ApiHelp before the pieces are joined together and returned.
2348 * This exists mainly for ApiMain to add the Permissions and Credits
2349 * sections. Other modules probably don't need it.
2351 * @param string[] &$help Array of help data
2352 * @param array $options Options passed to ApiHelp::getHelp
2353 * @param array &$tocData If a TOC is being generated, this array has keys
2354 * as anchors in the page and values as for Linker::generateTOC().
2356 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2361 /************************************************************************//**
2366 /// @deprecated since 1.24
2367 const PROP_ROOT
= 'ROOT';
2368 /// @deprecated since 1.24
2369 const PROP_LIST
= 'LIST';
2370 /// @deprecated since 1.24
2371 const PROP_TYPE
= 0;
2372 /// @deprecated since 1.24
2373 const PROP_NULLABLE
= 1;
2376 * Formerly returned a string that identifies the version of the extending
2377 * class. Typically included the class name, the svn revision, timestamp,
2378 * and last author. Usually done with SVN's Id keyword
2380 * @deprecated since 1.21, version string is no longer supported
2383 public function getVersion() {
2384 wfDeprecated( __METHOD__
, '1.21' );
2389 * Formerly used to fetch a list of possible properites in the result,
2390 * somehow organized with respect to the prop parameter that causes them to
2391 * be returned. The specific semantics of the return value was never
2392 * specified. Since this was never possible to be accurately updated, it
2395 * @deprecated since 1.24
2396 * @return array|bool
2398 protected function getResultProperties() {
2399 wfDeprecated( __METHOD__
, '1.24' );
2404 * @see self::getResultProperties()
2405 * @deprecated since 1.24
2406 * @return array|bool
2408 public function getFinalResultProperties() {
2409 wfDeprecated( __METHOD__
, '1.24' );
2414 * @see self::getResultProperties()
2415 * @deprecated since 1.24
2417 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2418 wfDeprecated( __METHOD__
, '1.24' );
2422 * @see self::getPossibleErrors()
2423 * @deprecated since 1.24
2426 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2427 wfDeprecated( __METHOD__
, '1.24' );
2432 * @see self::getPossibleErrors()
2433 * @deprecated since 1.24
2436 public function getRequireMaxOneParameterErrorMessages( $params ) {
2437 wfDeprecated( __METHOD__
, '1.24' );
2442 * @see self::getPossibleErrors()
2443 * @deprecated since 1.24
2446 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2447 wfDeprecated( __METHOD__
, '1.24' );
2452 * @see self::getPossibleErrors()
2453 * @deprecated since 1.24
2456 public function getTitleOrPageIdErrorMessage() {
2457 wfDeprecated( __METHOD__
, '1.24' );
2462 * This formerly attempted to return a list of all possible errors returned
2463 * by the module. However, this was impossible to maintain in many cases
2464 * since errors could come from other areas of MediaWiki and in some cases
2465 * from arbitrary extension hooks. Since a partial list claiming to be
2466 * comprehensive is unlikely to be useful, it was removed.
2468 * @deprecated since 1.24
2471 public function getPossibleErrors() {
2472 wfDeprecated( __METHOD__
, '1.24' );
2477 * @see self::getPossibleErrors()
2478 * @deprecated since 1.24
2481 public function getFinalPossibleErrors() {
2482 wfDeprecated( __METHOD__
, '1.24' );
2487 * @see self::getPossibleErrors()
2488 * @deprecated since 1.24
2491 public function parseErrors( $errors ) {
2492 wfDeprecated( __METHOD__
, '1.24' );
2497 * Returns the description string for this module
2499 * Ignored if an i18n message exists for
2500 * "apihelp-{$this->getModulePath()}-description".
2502 * @deprecated since 1.25
2503 * @return Message|string|array
2505 protected function getDescription() {
2510 * Returns an array of parameter descriptions.
2512 * For each parameter, ignored if an i18n message exists for the parameter.
2513 * By default that message is
2514 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2515 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2516 * self::getFinalParams().
2518 * @deprecated since 1.25
2519 * @return array|bool False on no parameter descriptions
2521 protected function getParamDescription() {
2526 * Returns usage examples for this module.
2528 * Return value as an array is either:
2529 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2531 * - sequential numeric keys with even-numbered keys being display-text
2532 * and odd-numbered keys being partial urls
2533 * - partial URLs as keys with display-text (string or array-to-be-joined)
2535 * Return value as a string is the same as an array with a numeric key and
2536 * that value, and boolean false means "no examples".
2538 * @deprecated since 1.25, use getExamplesMessages() instead
2539 * @return bool|string|array
2541 protected function getExamples() {
2546 * Generates help message for this module, or false if there is no description
2547 * @deprecated since 1.25
2548 * @return string|bool
2550 public function makeHelpMsg() {
2551 wfDeprecated( __METHOD__
, '1.25' );
2552 static $lnPrfx = "\n ";
2554 $msg = $this->getFinalDescription();
2556 if ( $msg !== false ) {
2558 if ( !is_array( $msg ) ) {
2563 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2565 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2567 if ( $this->isReadMode() ) {
2568 $msg .= "\nThis module requires read rights";
2570 if ( $this->isWriteMode() ) {
2571 $msg .= "\nThis module requires write rights";
2573 if ( $this->mustBePosted() ) {
2574 $msg .= "\nThis module only accepts POST requests";
2576 if ( $this->isReadMode() ||
$this->isWriteMode() ||
2577 $this->mustBePosted()
2583 $paramsMsg = $this->makeHelpMsgParameters();
2584 if ( $paramsMsg !== false ) {
2585 $msg .= "Parameters:\n$paramsMsg";
2588 $examples = $this->getExamples();
2590 if ( !is_array( $examples ) ) {
2595 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
2596 foreach ( $examples as $k => $v ) {
2597 if ( is_numeric( $k ) ) {
2600 if ( is_array( $v ) ) {
2601 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2603 $msgExample = " $v";
2606 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2616 * @deprecated since 1.25
2617 * @param string $item
2620 private function indentExampleText( $item ) {
2625 * @deprecated since 1.25
2626 * @param string $prefix Text to split output items
2627 * @param string $title What is being output
2628 * @param string|array $input
2631 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2632 wfDeprecated( __METHOD__
, '1.25' );
2633 if ( $input === false ) {
2636 if ( !is_array( $input ) ) {
2637 $input = array( $input );
2640 if ( count( $input ) > 0 ) {
2642 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
2646 $msg .= implode( $prefix, $input ) . "\n";
2655 * Generates the parameter descriptions for this module, to be displayed in the
2657 * @deprecated since 1.25
2658 * @return string|bool
2660 public function makeHelpMsgParameters() {
2661 wfDeprecated( __METHOD__
, '1.25' );
2662 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2664 $paramsDescription = $this->getFinalParamDescription();
2666 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2667 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2668 foreach ( $params as $paramName => $paramSettings ) {
2669 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
2670 if ( is_array( $desc ) ) {
2671 $desc = implode( $paramPrefix, $desc );
2675 if ( !is_array( $paramSettings ) ) {
2676 $paramSettings = array(
2677 self
::PARAM_DFLT
=> $paramSettings,
2681 //handle missing type
2682 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
2683 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
2684 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
2686 if ( is_bool( $dflt ) ) {
2687 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
2688 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
2689 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
2690 } elseif ( is_int( $dflt ) ) {
2691 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
2695 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
2696 && $paramSettings[self
::PARAM_DEPRECATED
]
2698 $desc = "DEPRECATED! $desc";
2701 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
2702 && $paramSettings[self
::PARAM_REQUIRED
]
2704 $desc .= $paramPrefix . "This parameter is required";
2707 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
2708 ?
$paramSettings[self
::PARAM_TYPE
]
2710 if ( isset( $type ) ) {
2711 $hintPipeSeparated = true;
2712 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
2713 ?
$paramSettings[self
::PARAM_ISMULTI
]
2716 $prompt = 'Values (separate with \'|\'): ';
2718 $prompt = 'One value: ';
2721 if ( $type === 'submodule' ) {
2722 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
2723 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
2725 $type = $this->getModuleManager()->getNames( $paramName );
2729 if ( is_array( $type ) ) {
2731 $nothingPrompt = '';
2732 foreach ( $type as $t ) {
2734 $nothingPrompt = 'Can be empty, or ';
2739 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2740 $choicesstring = implode( ', ', $choices );
2741 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2742 $hintPipeSeparated = false;
2746 // Special handling because namespaces are
2747 // type-limited, yet they are not given
2748 $desc .= $paramPrefix . $prompt;
2749 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2750 100, $descWordwrap );
2751 $hintPipeSeparated = false;
2754 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2755 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2756 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2758 $desc .= ' allowed';
2761 $s = $multi ?
's' : '';
2762 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2763 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2764 if ( $hasMin ||
$hasMax ) {
2766 $intRangeStr = "The value$s must be no less than " .
2767 "{$paramSettings[self::PARAM_MIN]}";
2768 } elseif ( !$hasMin ) {
2769 $intRangeStr = "The value$s must be no more than " .
2770 "{$paramSettings[self::PARAM_MAX]}";
2772 $intRangeStr = "The value$s must be between " .
2773 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2776 $desc .= $paramPrefix . $intRangeStr;
2780 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2786 if ( $hintPipeSeparated ) {
2787 $desc .= $paramPrefix . "Separate values with '|'";
2790 $isArray = is_array( $type );
2792 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2794 $desc .= $paramPrefix . "Maximum number of values " .
2795 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2800 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2801 if ( !is_null( $default ) && $default !== false ) {
2802 $desc .= $paramPrefix . "Default: $default";
2805 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2815 * @deprecated since 1.25, always returns empty string
2816 * @param DatabaseBase|bool $db
2819 public function getModuleProfileName( $db = false ) {
2820 wfDeprecated( __METHOD__
, '1.25' );
2825 * @deprecated since 1.25
2827 public function profileIn() {
2828 // No wfDeprecated() yet because extensions call this and might need to
2829 // keep doing so for BC.
2833 * @deprecated since 1.25
2835 public function profileOut() {
2836 // No wfDeprecated() yet because extensions call this and might need to
2837 // keep doing so for BC.
2841 * @deprecated since 1.25
2843 public function safeProfileOut() {
2844 wfDeprecated( __METHOD__
, '1.25' );
2848 * @deprecated since 1.25, always returns 0
2851 public function getProfileTime() {
2852 wfDeprecated( __METHOD__
, '1.25' );
2857 * @deprecated since 1.25
2859 public function profileDBIn() {
2860 wfDeprecated( __METHOD__
, '1.25' );
2864 * @deprecated since 1.25
2866 public function profileDBOut() {
2867 wfDeprecated( __METHOD__
, '1.25' );
2871 * @deprecated since 1.25, always returns 0
2874 public function getProfileDBTime() {
2875 wfDeprecated( __METHOD__
, '1.25' );
2880 * Get the result data array (read-only)
2881 * @deprecated since 1.25, use $this->getResult() methods instead
2884 public function getResultData() {
2885 wfDeprecated( __METHOD__
, '1.25' );
2886 return $this->getResult()->getData();
2890 * Call wfTransactionalTimeLimit() if this request was POSTed
2893 protected function useTransactionalTimeLimit() {
2894 if ( $this->getRequest()->wasPosted() ) {
2895 wfTransactionalTimeLimit();
2903 * For really cool vim folding this needs to be at the end:
2904 * vim: foldmarker=@{,@} foldmethod=marker