5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 const LIMIT_BIG1
= 500; // Fast query, std user limit
69 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
70 const LIMIT_SML1
= 50; // Slow query, std user limit
71 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
74 * getAllowedParams() flag: When set, the result could take longer to generate,
75 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
78 const GET_VALUES_FOR_HELP
= 1;
83 private $mModuleName, $mModulePrefix;
84 private $mSlaveDB = null;
85 private $mParamCache = array();
88 * @param ApiMain $mainModule
89 * @param string $moduleName Name of this module
90 * @param string $modulePrefix Prefix to use for parameter names
92 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
93 $this->mMainModule
= $mainModule;
94 $this->mModuleName
= $moduleName;
95 $this->mModulePrefix
= $modulePrefix;
97 if ( !$this->isMain() ) {
98 $this->setContext( $mainModule->getContext() );
103 /************************************************************************//**
104 * @name Methods to implement
109 * Evaluates the parameters, performs the requested query, and sets up
110 * the result. Concrete implementations of ApiBase must override this
111 * method to provide whatever functionality their module offers.
112 * Implementations must not produce any output on their own and are not
113 * expected to handle any errors.
115 * The execute() method will be invoked directly by ApiMain immediately
116 * before the result of the module is output. Aside from the
117 * constructor, implementations should assume that no other methods
118 * will be called externally on the module before the result is
121 * The result data should be stored in the ApiResult object available
122 * through getResult().
124 abstract public function execute();
127 * Get the module manager, or null if this module has no sub-modules
129 * @return ApiModuleManager
131 public function getModuleManager() {
136 * If the module may only be used with a certain format module,
137 * it should override this method to return an instance of that formatter.
138 * A value of null means the default format will be used.
139 * @return mixed Instance of a derived class of ApiFormatBase, or null
141 public function getCustomPrinter() {
146 * Returns the description string for this module
147 * @return string|array
149 protected function getDescription() {
154 * Returns usage examples for this module. Return false if no examples are available.
155 * @return bool|string|array
157 protected function getExamples() {
162 * @return bool|string|array Returns a false if the module has no help URL,
163 * else returns a (array of) string
165 public function getHelpUrls() {
170 * Returns an array of allowed parameters (parameter name) => (default
171 * value) or (parameter name) => (array with PARAM_* constants as keys)
172 * Don't call this function directly: use getFinalParams() to allow
173 * hooks to modify parameters as needed.
175 * Some derived classes may choose to handle an integer $flags parameter
176 * in the overriding methods. Callers of this method can pass zero or
177 * more OR-ed flags like GET_VALUES_FOR_HELP.
181 protected function getAllowedParams( /* $flags = 0 */ ) {
182 // int $flags is not declared because it causes "Strict standards"
183 // warning. Most derived classes do not implement it.
188 * Returns an array of parameter descriptions.
189 * Don't call this function directly: use getFinalParamDescription() to
190 * allow hooks to modify descriptions as needed.
191 * @return array|bool False on no parameter descriptions
193 protected function getParamDescription() {
198 * Indicates if this module needs maxlag to be checked
201 public function shouldCheckMaxlag() {
206 * Indicates whether this module requires read rights
209 public function isReadMode() {
214 * Indicates whether this module requires write mode
217 public function isWriteMode() {
222 * Indicates whether this module must be called with a POST request
225 public function mustBePosted() {
226 return $this->needsToken() !== false;
230 * Returns the token type this module requires in order to execute.
232 * Modules are strongly encouraged to use the core 'csrf' type unless they
233 * have specialized security needs. If the token type is not one of the
234 * core types, you must use the ApiQueryTokensRegisterTypes hook to
237 * Returning a non-falsey value here will cause self::getFinalParams() to
238 * return a required string 'token' parameter and
239 * self::getFinalParamDescription() to ensure there is standardized
240 * documentation for it. Also, self::mustBePosted() must return true when
243 * In previous versions of MediaWiki, true was a valid return value.
244 * Returning true will generate errors indicating that the API module needs
247 * @return string|false
249 public function needsToken() {
254 * Fetch the salt used in the Web UI corresponding to this module.
256 * Only override this if the Web UI uses a token with a non-constant salt.
259 * @param array $params All supplied parameters for the module
260 * @return string|array|null
262 protected function getWebUITokenSalt( array $params ) {
268 /************************************************************************//**
269 * @name Data access methods
274 * Get the name of the module being executed by this instance
277 public function getModuleName() {
278 return $this->mModuleName
;
282 * Get parameter prefix (usually two letters or an empty string).
285 public function getModulePrefix() {
286 return $this->mModulePrefix
;
290 * Get the main module
293 public function getMain() {
294 return $this->mMainModule
;
298 * Returns true if this module is the main module ($this === $this->mMainModule),
302 public function isMain() {
303 return $this === $this->mMainModule
;
307 * Get the result object
310 public function getResult() {
311 // Main module has getResult() method overridden
312 // Safety - avoid infinite loop:
313 if ( $this->isMain() ) {
314 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
317 return $this->getMain()->getResult();
321 * Get the result data array (read-only)
324 public function getResultData() {
325 return $this->getResult()->getData();
329 * Gets a default slave database connection object
330 * @return DatabaseBase
332 protected function getDB() {
333 if ( !isset( $this->mSlaveDB
) ) {
334 $this->profileDBIn();
335 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
336 $this->profileDBOut();
339 return $this->mSlaveDB
;
343 * Get final module description, after hooks have had a chance to tweak it as
346 * @return array|bool False on no parameters
348 public function getFinalDescription() {
349 $desc = $this->getDescription();
350 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
356 * Get final list of parameters, after hooks have had a chance to
357 * tweak it as needed.
359 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
360 * @return array|bool False on no parameters
361 * @since 1.21 $flags param added
363 public function getFinalParams( $flags = 0 ) {
364 $params = $this->getAllowedParams( $flags );
366 if ( $this->needsToken() ) {
367 $params['token'] = array(
368 ApiBase
::PARAM_TYPE
=> 'string',
369 ApiBase
::PARAM_REQUIRED
=> true,
373 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
379 * Get final parameter descriptions, after hooks have had a chance to tweak it as
382 * @return array|bool False on no parameter descriptions
384 public function getFinalParamDescription() {
385 $desc = $this->getParamDescription();
387 $tokenType = $this->needsToken();
389 if ( !isset( $desc['token'] ) ) {
390 $desc['token'] = array();
391 } elseif ( !is_array( $desc['token'] ) ) {
392 // We ignore a plain-string token, because it's probably an
393 // extension that is supplying the string for BC.
394 $desc['token'] = array();
396 array_unshift( $desc['token'],
397 "A '$tokenType' token retrieved from action=query&meta=tokens"
401 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
408 /************************************************************************//**
409 * @name Parameter handling
414 * This method mangles parameter name based on the prefix supplied to the constructor.
415 * Override this method to change parameter name during runtime
416 * @param string $paramName Parameter name
417 * @return string Prefixed parameter name
419 public function encodeParamName( $paramName ) {
420 return $this->mModulePrefix
. $paramName;
424 * Using getAllowedParams(), this function makes an array of the values
425 * provided by the user, with key being the name of the variable, and
426 * value - validated value from user or default. limits will not be
427 * parsed if $parseLimit is set to false; use this when the max
428 * limit is not definitive yet, e.g. when getting revisions.
429 * @param bool $parseLimit True by default
432 public function extractRequestParams( $parseLimit = true ) {
433 // Cache parameters, for performance and to avoid bug 24564.
434 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
435 $params = $this->getFinalParams();
438 if ( $params ) { // getFinalParams() can return false
439 foreach ( $params as $paramName => $paramSettings ) {
440 $results[$paramName] = $this->getParameterFromSettings(
441 $paramName, $paramSettings, $parseLimit );
444 $this->mParamCache
[$parseLimit] = $results;
447 return $this->mParamCache
[$parseLimit];
451 * Get a value for the given parameter
452 * @param string $paramName Parameter name
453 * @param bool $parseLimit See extractRequestParams()
454 * @return mixed Parameter value
456 protected function getParameter( $paramName, $parseLimit = true ) {
457 $params = $this->getFinalParams();
458 $paramSettings = $params[$paramName];
460 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
464 * Die if none or more than one of a certain set of parameters is set and not false.
466 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
467 * @param string $required,... Names of parameters of which exactly one must be set
469 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
470 $required = func_get_args();
471 array_shift( $required );
472 $p = $this->getModulePrefix();
474 $intersection = array_intersect( array_keys( array_filter( $params,
475 array( $this, "parameterNotEmpty" ) ) ), $required );
477 if ( count( $intersection ) > 1 ) {
479 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
481 } elseif ( count( $intersection ) == 0 ) {
483 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
490 * Die if more than one of a certain set of parameters is set and not false.
492 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
493 * @param string $required,... Names of parameters of which at most one must be set
495 public function requireMaxOneParameter( $params, $required /*...*/ ) {
496 $required = func_get_args();
497 array_shift( $required );
498 $p = $this->getModulePrefix();
500 $intersection = array_intersect( array_keys( array_filter( $params,
501 array( $this, "parameterNotEmpty" ) ) ), $required );
503 if ( count( $intersection ) > 1 ) {
505 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
512 * Die if none of a certain set of parameters is set and not false.
515 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
516 * @param string $required,... Names of parameters of which at least one must be set
518 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
519 $required = func_get_args();
520 array_shift( $required );
521 $p = $this->getModulePrefix();
523 $intersection = array_intersect(
524 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
528 if ( count( $intersection ) == 0 ) {
529 $this->dieUsage( "At least one of the parameters {$p}" .
530 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
535 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
537 * @param object $x Parameter to check is not null/false
540 private function parameterNotEmpty( $x ) {
541 return !is_null( $x ) && $x !== false;
545 * Get a WikiPage object from a title or pageid param, if possible.
546 * Can die, if no param is set or if the title or page id is not valid.
548 * @param array $params
549 * @param bool|string $load Whether load the object's state from the database:
550 * - false: don't load (if the pageid is given, it will still be loaded)
551 * - 'fromdb': load from a slave database
552 * - 'fromdbmaster': load from the master database
555 public function getTitleOrPageId( $params, $load = false ) {
556 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
559 if ( isset( $params['title'] ) ) {
560 $titleObj = Title
::newFromText( $params['title'] );
561 if ( !$titleObj ||
$titleObj->isExternal() ) {
562 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
564 if ( !$titleObj->canExist() ) {
565 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
567 $pageObj = WikiPage
::factory( $titleObj );
568 if ( $load !== false ) {
569 $pageObj->loadPageData( $load );
571 } elseif ( isset( $params['pageid'] ) ) {
572 if ( $load === false ) {
575 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
577 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
585 * Return true if we're to watch the page, false if not, null if no change.
586 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
587 * @param Title $titleObj The page under consideration
588 * @param string $userOption The user option to consider when $watchlist=preferences.
589 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
592 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
594 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
596 switch ( $watchlist ) {
604 # If the user is already watching, don't bother checking
605 if ( $userWatching ) {
608 # If no user option was passed, use watchdefault and watchcreations
609 if ( is_null( $userOption ) ) {
610 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
611 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
614 # Watch the article based on the user preference
615 return $this->getUser()->getBoolOption( $userOption );
618 return $userWatching;
621 return $userWatching;
626 * Using the settings determine the value for the given parameter
628 * @param string $paramName Parameter name
629 * @param array|mixed $paramSettings Default value or an array of settings
630 * using PARAM_* constants.
631 * @param bool $parseLimit Parse limit?
632 * @return mixed Parameter value
634 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
635 // Some classes may decide to change parameter names
636 $encParamName = $this->encodeParamName( $paramName );
638 if ( !is_array( $paramSettings ) ) {
639 $default = $paramSettings;
641 $type = gettype( $paramSettings );
646 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
647 ?
$paramSettings[self
::PARAM_DFLT
]
649 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
650 ?
$paramSettings[self
::PARAM_ISMULTI
]
652 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
653 ?
$paramSettings[self
::PARAM_TYPE
]
655 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
656 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
658 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
659 ?
$paramSettings[self
::PARAM_DEPRECATED
]
661 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
662 ?
$paramSettings[self
::PARAM_REQUIRED
]
665 // When type is not given, and no choices, the type is the same as $default
666 if ( !isset( $type ) ) {
667 if ( isset( $default ) ) {
668 $type = gettype( $default );
670 $type = 'NULL'; // allow everything
675 if ( $type == 'boolean' ) {
676 if ( isset( $default ) && $default !== false ) {
677 // Having a default value of anything other than 'false' is not allowed
680 "Boolean param $encParamName's default is set to '$default'. " .
681 "Boolean parameters must default to false."
685 $value = $this->getMain()->getCheck( $encParamName );
686 } elseif ( $type == 'upload' ) {
687 if ( isset( $default ) ) {
688 // Having a default value is not allowed
691 "File upload param $encParamName's default is set to " .
692 "'$default'. File upload parameters may not have a default." );
695 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
697 $value = $this->getMain()->getUpload( $encParamName );
698 if ( !$value->exists() ) {
699 // This will get the value without trying to normalize it
700 // (because trying to normalize a large binary file
701 // accidentally uploaded as a field fails spectacularly)
702 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
703 if ( $value !== null ) {
705 "File upload param $encParamName is not a file upload; " .
706 "be sure to use multipart/form-data for your POST and include " .
707 "a filename in the Content-Disposition header.",
708 "badupload_{$encParamName}"
713 $value = $this->getMain()->getVal( $encParamName, $default );
715 if ( isset( $value ) && $type == 'namespace' ) {
716 $type = MWNamespace
::getValidNamespaces();
718 if ( isset( $value ) && $type == 'submodule' ) {
719 $type = $this->getModuleManager()->getNames( $paramName );
723 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
724 $value = $this->parseMultiValue(
728 is_array( $type ) ?
$type : null
732 // More validation only when choices were not given
733 // choices were validated in parseMultiValue()
734 if ( isset( $value ) ) {
735 if ( !is_array( $type ) ) {
737 case 'NULL': // nothing to do
740 if ( $required && $value === '' ) {
741 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
744 case 'integer': // Force everything using intval() and optionally validate limits
745 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
746 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
747 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
748 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
750 if ( is_array( $value ) ) {
751 $value = array_map( 'intval', $value );
752 if ( !is_null( $min ) ||
!is_null( $max ) ) {
753 foreach ( $value as &$v ) {
754 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
758 $value = intval( $value );
759 if ( !is_null( $min ) ||
!is_null( $max ) ) {
760 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
765 if ( !$parseLimit ) {
766 // Don't do any validation whatsoever
769 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
770 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
774 "MAX1 or MAX2 are not defined for the limit $encParamName"
778 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
780 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
781 if ( $value == 'max' ) {
782 $value = $this->getMain()->canApiHighLimits()
783 ?
$paramSettings[self
::PARAM_MAX2
]
784 : $paramSettings[self
::PARAM_MAX
];
785 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
787 $value = intval( $value );
788 $this->validateLimit(
792 $paramSettings[self
::PARAM_MAX
],
793 $paramSettings[self
::PARAM_MAX2
]
799 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
803 if ( is_array( $value ) ) {
804 foreach ( $value as $key => $val ) {
805 $value[$key] = $this->validateTimestamp( $val, $encParamName );
808 $value = $this->validateTimestamp( $value, $encParamName );
812 if ( is_array( $value ) ) {
813 foreach ( $value as $key => $val ) {
814 $value[$key] = $this->validateUser( $val, $encParamName );
817 $value = $this->validateUser( $value, $encParamName );
820 case 'upload': // nothing to do
823 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
827 // Throw out duplicates if requested
828 if ( !$dupes && is_array( $value ) ) {
829 $value = array_unique( $value );
832 // Set a warning if a deprecated parameter has been passed
833 if ( $deprecated && $value !== false ) {
834 $this->setWarning( "The $encParamName parameter has been deprecated." );
836 } elseif ( $required ) {
837 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
844 * Return an array of values that were given in a 'a|b|c' notation,
845 * after it optionally validates them against the list allowed values.
847 * @param string $valueName The name of the parameter (for error
849 * @param mixed $value The value being parsed
850 * @param bool $allowMultiple Can $value contain more than one value
852 * @param string[]|null $allowedValues An array of values to check against. If
853 * null, all values are accepted.
854 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
856 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
857 if ( trim( $value ) === '' && $allowMultiple ) {
861 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
862 // because it unstubs $wgUser
863 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
864 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
868 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
869 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
870 "the limit is $sizeLimit" );
873 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
874 // Bug 33482 - Allow entries with | in them for non-multiple values
875 if ( in_array( $value, $allowedValues, true ) ) {
879 $possibleValues = is_array( $allowedValues )
880 ?
"of '" . implode( "', '", $allowedValues ) . "'"
883 "Only one $possibleValues is allowed for parameter '$valueName'",
884 "multival_$valueName"
888 if ( is_array( $allowedValues ) ) {
889 // Check for unknown values
890 $unknown = array_diff( $valuesList, $allowedValues );
891 if ( count( $unknown ) ) {
892 if ( $allowMultiple ) {
893 $s = count( $unknown ) > 1 ?
's' : '';
894 $vals = implode( ", ", $unknown );
895 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
898 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
903 // Now throw them out
904 $valuesList = array_intersect( $valuesList, $allowedValues );
907 return $allowMultiple ?
$valuesList : $valuesList[0];
911 * Validate the value against the minimum and user/bot maximum limits.
912 * Prints usage info on failure.
913 * @param string $paramName Parameter name
914 * @param int $value Parameter value
915 * @param int|null $min Minimum value
916 * @param int|null $max Maximum value for users
917 * @param int $botMax Maximum value for sysops/bots
918 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
920 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
921 if ( !is_null( $min ) && $value < $min ) {
923 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
924 $this->warnOrDie( $msg, $enforceLimits );
928 // Minimum is always validated, whereas maximum is checked only if not
929 // running in internal call mode
930 if ( $this->getMain()->isInternalMode() ) {
934 // Optimization: do not check user's bot status unless really needed -- skips db query
935 // assumes $botMax >= $max
936 if ( !is_null( $max ) && $value > $max ) {
937 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
938 if ( $value > $botMax ) {
939 $msg = $this->encodeParamName( $paramName ) .
940 " may not be over $botMax (set to $value) for bots or sysops";
941 $this->warnOrDie( $msg, $enforceLimits );
945 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
946 $this->warnOrDie( $msg, $enforceLimits );
953 * Validate and normalize of parameters of type 'timestamp'
954 * @param string $value Parameter value
955 * @param string $encParamName Parameter name
956 * @return string Validated and normalized parameter
958 protected function validateTimestamp( $value, $encParamName ) {
959 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
960 if ( $unixTimestamp === false ) {
962 "Invalid value '$value' for timestamp parameter $encParamName",
963 "badtimestamp_{$encParamName}"
967 return wfTimestamp( TS_MW
, $unixTimestamp );
971 * Validate the supplied token.
974 * @param string $token Supplied token
975 * @param array $params All supplied parameters for the module
978 public final function validateToken( $token, array $params ) {
979 $tokenType = $this->needsToken();
980 $salts = ApiQueryTokens
::getTokenTypeSalts();
981 if ( !isset( $salts[$tokenType] ) ) {
982 throw new MWException(
983 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
984 'without registering it'
988 if ( $this->getUser()->matchEditToken(
996 $webUiSalt = $this->getWebUITokenSalt( $params );
997 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1009 * Validate and normalize of parameters of type 'user'
1010 * @param string $value Parameter value
1011 * @param string $encParamName Parameter name
1012 * @return string Validated and normalized parameter
1014 private function validateUser( $value, $encParamName ) {
1015 $title = Title
::makeTitleSafe( NS_USER
, $value );
1016 if ( $title === null ) {
1018 "Invalid value '$value' for user parameter $encParamName",
1019 "baduser_{$encParamName}"
1023 return $title->getText();
1028 /************************************************************************//**
1029 * @name Utility methods
1034 * Set a watch (or unwatch) based the based on a watchlist parameter.
1035 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1036 * @param Title $titleObj The article's title to change
1037 * @param string $userOption The user option to consider when $watch=preferences
1039 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1040 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1041 if ( $value === null ) {
1045 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1049 * Truncate an array to a certain length.
1050 * @param array $arr Array to truncate
1051 * @param int $limit Maximum length
1052 * @return bool True if the array was truncated, false otherwise
1054 public static function truncateArray( &$arr, $limit ) {
1056 while ( count( $arr ) > $limit ) {
1065 * Gets the user for whom to get the watchlist
1067 * @param array $params
1070 public function getWatchlistUser( $params ) {
1071 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1072 $user = User
::newFromName( $params['owner'], false );
1073 if ( !( $user && $user->getId() ) ) {
1074 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1076 $token = $user->getOption( 'watchlisttoken' );
1077 if ( $token == '' ||
$token != $params['token'] ) {
1079 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1084 if ( !$this->getUser()->isLoggedIn() ) {
1085 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1087 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1088 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1090 $user = $this->getUser();
1098 /************************************************************************//**
1099 * @name Warning and error reporting
1104 * Set warning section for this module. Users should monitor this
1105 * section to notice any changes in API. Multiple calls to this
1106 * function will result in the warning messages being separated by
1108 * @param string $warning Warning message
1110 public function setWarning( $warning ) {
1111 $result = $this->getResult();
1112 $data = $result->getData();
1113 $moduleName = $this->getModuleName();
1114 if ( isset( $data['warnings'][$moduleName] ) ) {
1115 // Don't add duplicate warnings
1116 $oldWarning = $data['warnings'][$moduleName]['*'];
1117 $warnPos = strpos( $oldWarning, $warning );
1118 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1119 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
1120 // Check if $warning is followed by "\n" or the end of the $oldWarning
1121 $warnPos +
= strlen( $warning );
1122 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
1126 // If there is a warning already, append it to the existing one
1127 $warning = "$oldWarning\n$warning";
1130 ApiResult
::setContent( $msg, $warning );
1131 $result->addValue( 'warnings', $moduleName,
1132 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
1136 * Adds a warning to the output, else dies
1138 * @param string $msg Message to show as a warning, or error message if dying
1139 * @param bool $enforceLimits Whether this is an enforce (die)
1141 private function warnOrDie( $msg, $enforceLimits = false ) {
1142 if ( $enforceLimits ) {
1143 $this->dieUsage( $msg, 'integeroutofrange' );
1146 $this->setWarning( $msg );
1150 * Throw a UsageException, which will (if uncaught) call the main module's
1151 * error handler and die with an error message.
1153 * @param string $description One-line human-readable description of the
1154 * error condition, e.g., "The API requires a valid action parameter"
1155 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1156 * automated identification of the error, e.g., 'unknown_action'
1157 * @param int $httpRespCode HTTP response code
1158 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1159 * @throws UsageException
1161 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1162 Profiler
::instance()->close();
1163 throw new UsageException(
1165 $this->encodeParamName( $errorCode ),
1172 * Get error (as code, string) from a Status object.
1175 * @param Status $status
1176 * @return array Array of code and error string
1178 public function getErrorFromStatus( $status ) {
1179 if ( $status->isGood() ) {
1180 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1183 $errors = $status->getErrorsArray();
1185 // No errors? Assume the warnings should be treated as errors
1186 $errors = $status->getWarningsArray();
1189 // Still no errors? Punt
1190 $errors = array( array( 'unknownerror-nocode' ) );
1193 // Cannot use dieUsageMsg() because extensions might return custom
1195 if ( $errors[0] instanceof Message
) {
1197 $code = $msg->getKey();
1199 $code = array_shift( $errors[0] );
1200 $msg = wfMessage( $code, $errors[0] );
1202 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1203 // Translate message to code, for backwards compatibility
1204 $code = ApiBase
::$messageMap[$code]['code'];
1207 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1211 * Throw a UsageException based on the errors in the Status object.
1214 * @param Status $status
1215 * @throws MWException
1217 public function dieStatus( $status ) {
1219 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1220 $this->dieUsage( $msg, $code );
1223 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1225 * Array that maps message keys to error messages. $1 and friends are replaced.
1227 public static $messageMap = array(
1228 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1229 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1230 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1232 // Messages from Title::getUserPermissionsErrors()
1233 'ns-specialprotected' => array(
1234 'code' => 'unsupportednamespace',
1235 'info' => "Pages in the Special namespace can't be edited"
1237 'protectedinterface' => array(
1238 'code' => 'protectednamespace-interface',
1239 'info' => "You're not allowed to edit interface messages"
1241 'namespaceprotected' => array(
1242 'code' => 'protectednamespace',
1243 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1245 'customcssprotected' => array(
1246 'code' => 'customcssprotected',
1247 'info' => "You're not allowed to edit custom CSS pages"
1249 'customjsprotected' => array(
1250 'code' => 'customjsprotected',
1251 'info' => "You're not allowed to edit custom JavaScript pages"
1253 'cascadeprotected' => array(
1254 'code' => 'cascadeprotected',
1255 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1257 'protectedpagetext' => array(
1258 'code' => 'protectedpage',
1259 'info' => "The \"\$1\" right is required to edit this page"
1261 'protect-cantedit' => array(
1262 'code' => 'cantedit',
1263 'info' => "You can't protect this page because you can't edit it"
1265 'deleteprotected' => array(
1266 'code' => 'cantedit',
1267 'info' => "You can't delete this page because it has been protected"
1269 'badaccess-group0' => array(
1270 'code' => 'permissiondenied',
1271 'info' => "Permission denied"
1272 ), // Generic permission denied message
1273 'badaccess-groups' => array(
1274 'code' => 'permissiondenied',
1275 'info' => "Permission denied"
1277 'titleprotected' => array(
1278 'code' => 'protectedtitle',
1279 'info' => "This title has been protected from creation"
1281 'nocreate-loggedin' => array(
1282 'code' => 'cantcreate',
1283 'info' => "You don't have permission to create new pages"
1285 'nocreatetext' => array(
1286 'code' => 'cantcreate-anon',
1287 'info' => "Anonymous users can't create new pages"
1289 'movenologintext' => array(
1290 'code' => 'cantmove-anon',
1291 'info' => "Anonymous users can't move pages"
1293 'movenotallowed' => array(
1294 'code' => 'cantmove',
1295 'info' => "You don't have permission to move pages"
1297 'confirmedittext' => array(
1298 'code' => 'confirmemail',
1299 'info' => "You must confirm your email address before you can edit"
1301 'blockedtext' => array(
1302 'code' => 'blocked',
1303 'info' => "You have been blocked from editing"
1305 'autoblockedtext' => array(
1306 'code' => 'autoblocked',
1307 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1310 // Miscellaneous interface messages
1311 'actionthrottledtext' => array(
1312 'code' => 'ratelimited',
1313 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1315 'alreadyrolled' => array(
1316 'code' => 'alreadyrolled',
1317 'info' => "The page you tried to rollback was already rolled back"
1319 'cantrollback' => array(
1320 'code' => 'onlyauthor',
1321 'info' => "The page you tried to rollback only has one author"
1323 'readonlytext' => array(
1324 'code' => 'readonly',
1325 'info' => "The wiki is currently in read-only mode"
1327 'sessionfailure' => array(
1328 'code' => 'badtoken',
1329 'info' => "Invalid token" ),
1330 'cannotdelete' => array(
1331 'code' => 'cantdelete',
1332 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1334 'notanarticle' => array(
1335 'code' => 'missingtitle',
1336 'info' => "The page you requested doesn't exist"
1338 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1340 'immobile_namespace' => array(
1341 'code' => 'immobilenamespace',
1342 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1344 'articleexists' => array(
1345 'code' => 'articleexists',
1346 'info' => "The destination article already exists and is not a redirect to the source article"
1348 'protectedpage' => array(
1349 'code' => 'protectedpage',
1350 'info' => "You don't have permission to perform this move"
1352 'hookaborted' => array(
1353 'code' => 'hookaborted',
1354 'info' => "The modification you tried to make was aborted by an extension hook"
1356 'cantmove-titleprotected' => array(
1357 'code' => 'protectedtitle',
1358 'info' => "The destination article has been protected from creation"
1360 'imagenocrossnamespace' => array(
1361 'code' => 'nonfilenamespace',
1362 'info' => "Can't move a file to a non-file namespace"
1364 'imagetypemismatch' => array(
1365 'code' => 'filetypemismatch',
1366 'info' => "The new file extension doesn't match its type"
1368 // 'badarticleerror' => shouldn't happen
1369 // 'badtitletext' => shouldn't happen
1370 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1371 'range_block_disabled' => array(
1372 'code' => 'rangedisabled',
1373 'info' => "Blocking IP ranges has been disabled"
1375 'nosuchusershort' => array(
1376 'code' => 'nosuchuser',
1377 'info' => "The user you specified doesn't exist"
1379 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1380 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1381 'ipb_already_blocked' => array(
1382 'code' => 'alreadyblocked',
1383 'info' => "The user you tried to block was already blocked"
1385 'ipb_blocked_as_range' => array(
1386 'code' => 'blockedasrange',
1387 '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."
1389 'ipb_cant_unblock' => array(
1390 'code' => 'cantunblock',
1391 'info' => "The block you specified was not found. It may have been unblocked already"
1393 'mailnologin' => array(
1394 'code' => 'cantsend',
1395 '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"
1397 'ipbblocked' => array(
1398 'code' => 'ipbblocked',
1399 'info' => 'You cannot block or unblock users while you are yourself blocked'
1401 'ipbnounblockself' => array(
1402 'code' => 'ipbnounblockself',
1403 'info' => 'You are not allowed to unblock yourself'
1405 'usermaildisabled' => array(
1406 'code' => 'usermaildisabled',
1407 'info' => "User email has been disabled"
1409 'blockedemailuser' => array(
1410 'code' => 'blockedfrommail',
1411 'info' => "You have been blocked from sending email"
1413 'notarget' => array(
1414 'code' => 'notarget',
1415 'info' => "You have not specified a valid target for this action"
1418 'code' => 'noemail',
1419 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1421 'rcpatroldisabled' => array(
1422 'code' => 'patroldisabled',
1423 'info' => "Patrolling is disabled on this wiki"
1425 'markedaspatrollederror-noautopatrol' => array(
1426 'code' => 'noautopatrol',
1427 'info' => "You don't have permission to patrol your own changes"
1429 'delete-toobig' => array(
1430 'code' => 'bigdelete',
1431 'info' => "You can't delete this page because it has more than \$1 revisions"
1433 'movenotallowedfile' => array(
1434 'code' => 'cantmovefile',
1435 'info' => "You don't have permission to move files"
1437 'userrights-no-interwiki' => array(
1438 'code' => 'nointerwikiuserrights',
1439 'info' => "You don't have permission to change user rights on other wikis"
1441 'userrights-nodatabase' => array(
1442 'code' => 'nosuchdatabase',
1443 'info' => "Database \"\$1\" does not exist or is not local"
1445 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1446 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1447 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1448 'import-rootpage-invalid' => array(
1449 'code' => 'import-rootpage-invalid',
1450 'info' => 'Root page is an invalid title'
1452 'import-rootpage-nosubpage' => array(
1453 'code' => 'import-rootpage-nosubpage',
1454 'info' => 'Namespace "$1" of the root page does not allow subpages'
1457 // API-specific messages
1458 'readrequired' => array(
1459 'code' => 'readapidenied',
1460 'info' => "You need read permission to use this module"
1462 'writedisabled' => array(
1463 'code' => 'noapiwrite',
1464 '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"
1466 'writerequired' => array(
1467 'code' => 'writeapidenied',
1468 'info' => "You're not allowed to edit this wiki through the API"
1470 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1471 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1472 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1473 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1474 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1475 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1476 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1477 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1478 'create-titleexists' => array(
1479 'code' => 'create-titleexists',
1480 'info' => "Existing titles can't be protected with 'create'"
1482 'missingtitle-createonly' => array(
1483 'code' => 'missingtitle-createonly',
1484 'info' => "Missing titles can only be protected with 'create'"
1486 'cantblock' => array( 'code' => 'cantblock',
1487 'info' => "You don't have permission to block users"
1489 'canthide' => array(
1490 'code' => 'canthide',
1491 'info' => "You don't have permission to hide user names from the block log"
1493 'cantblock-email' => array(
1494 'code' => 'cantblock-email',
1495 'info' => "You don't have permission to block users from sending email through the wiki"
1497 'unblock-notarget' => array(
1498 'code' => 'notarget',
1499 'info' => "Either the id or the user parameter must be set"
1501 'unblock-idanduser' => array(
1502 'code' => 'idanduser',
1503 'info' => "The id and user parameters can't be used together"
1505 'cantunblock' => array(
1506 'code' => 'permissiondenied',
1507 'info' => "You don't have permission to unblock users"
1509 'cannotundelete' => array(
1510 'code' => 'cantundelete',
1511 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1513 'permdenied-undelete' => array(
1514 'code' => 'permissiondenied',
1515 'info' => "You don't have permission to restore deleted revisions"
1517 'createonly-exists' => array(
1518 'code' => 'articleexists',
1519 'info' => "The article you tried to create has been created already"
1521 'nocreate-missing' => array(
1522 'code' => 'missingtitle',
1523 'info' => "The article you tried to edit doesn't exist"
1525 'nosuchrcid' => array(
1526 'code' => 'nosuchrcid',
1527 'info' => "There is no change with rcid \"\$1\""
1529 'protect-invalidaction' => array(
1530 'code' => 'protect-invalidaction',
1531 'info' => "Invalid protection type \"\$1\""
1533 'protect-invalidlevel' => array(
1534 'code' => 'protect-invalidlevel',
1535 'info' => "Invalid protection level \"\$1\""
1537 'toofewexpiries' => array(
1538 'code' => 'toofewexpiries',
1539 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1541 'cantimport' => array(
1542 'code' => 'cantimport',
1543 'info' => "You don't have permission to import pages"
1545 'cantimport-upload' => array(
1546 'code' => 'cantimport-upload',
1547 'info' => "You don't have permission to import uploaded pages"
1549 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1550 'importuploaderrorsize' => array(
1551 'code' => 'filetoobig',
1552 'info' => 'The file you uploaded is bigger than the maximum upload size'
1554 'importuploaderrorpartial' => array(
1555 'code' => 'partialupload',
1556 'info' => 'The file was only partially uploaded'
1558 'importuploaderrortemp' => array(
1559 'code' => 'notempdir',
1560 'info' => 'The temporary upload directory is missing'
1562 'importcantopen' => array(
1563 'code' => 'cantopenfile',
1564 'info' => "Couldn't open the uploaded file"
1566 'import-noarticle' => array(
1567 'code' => 'badinterwiki',
1568 'info' => 'Invalid interwiki title specified'
1570 'importbadinterwiki' => array(
1571 'code' => 'badinterwiki',
1572 'info' => 'Invalid interwiki title specified'
1574 'import-unknownerror' => array(
1575 'code' => 'import-unknownerror',
1576 'info' => "Unknown error on import: \"\$1\""
1578 'cantoverwrite-sharedfile' => array(
1579 'code' => 'cantoverwrite-sharedfile',
1580 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1582 'sharedfile-exists' => array(
1583 'code' => 'fileexists-sharedrepo-perm',
1584 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1586 'mustbeposted' => array(
1587 'code' => 'mustbeposted',
1588 'info' => "The \$1 module requires a POST request"
1592 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1594 'specialpage-cantexecute' => array(
1595 'code' => 'specialpage-cantexecute',
1596 'info' => "You don't have permission to view the results of this special page"
1598 'invalidoldimage' => array(
1599 'code' => 'invalidoldimage',
1600 'info' => 'The oldimage parameter has invalid format'
1602 'nodeleteablefile' => array(
1603 'code' => 'nodeleteablefile',
1604 'info' => 'No such old version of the file'
1606 'fileexists-forbidden' => array(
1607 'code' => 'fileexists-forbidden',
1608 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1610 'fileexists-shared-forbidden' => array(
1611 'code' => 'fileexists-shared-forbidden',
1612 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1614 'filerevert-badversion' => array(
1615 'code' => 'filerevert-badversion',
1616 'info' => 'There is no previous local version of this file with the provided timestamp.'
1619 // ApiEditPage messages
1620 'noimageredirect-anon' => array(
1621 'code' => 'noimageredirect-anon',
1622 'info' => "Anonymous users can't create image redirects"
1624 'noimageredirect-logged' => array(
1625 'code' => 'noimageredirect',
1626 'info' => "You don't have permission to create image redirects"
1628 'spamdetected' => array(
1629 'code' => 'spamdetected',
1630 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1632 'contenttoobig' => array(
1633 'code' => 'contenttoobig',
1634 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1636 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1637 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1638 'wasdeleted' => array(
1639 'code' => 'pagedeleted',
1640 'info' => "The page has been deleted since you fetched its timestamp"
1642 'blankpage' => array(
1643 'code' => 'emptypage',
1644 'info' => "Creating new, empty pages is not allowed"
1646 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1647 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1648 'missingtext' => array(
1650 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1652 'emptynewsection' => array(
1653 'code' => 'emptynewsection',
1654 'info' => 'Creating empty new sections is not possible.'
1656 'revwrongpage' => array(
1657 'code' => 'revwrongpage',
1658 'info' => "r\$1 is not a revision of \"\$2\""
1660 'undo-failure' => array(
1661 'code' => 'undofailure',
1662 'info' => 'Undo failed due to conflicting intermediate edits'
1664 'content-not-allowed-here' => array(
1665 'code' => 'contentnotallowedhere',
1666 'info' => 'Content model "$1" is not allowed at title "$2"'
1669 // Messages from WikiPage::doEit()
1670 'edit-hook-aborted' => array(
1671 'code' => 'edit-hook-aborted',
1672 'info' => "Your edit was aborted by an ArticleSave hook"
1674 'edit-gone-missing' => array(
1675 'code' => 'edit-gone-missing',
1676 'info' => "The page you tried to edit doesn't seem to exist anymore"
1678 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1679 'edit-already-exists' => array(
1680 'code' => 'edit-already-exists',
1681 'info' => 'It seems the page you tried to create already exist'
1685 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1686 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1687 'uploaddisabled' => array(
1688 'code' => 'uploaddisabled',
1689 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1691 'copyuploaddisabled' => array(
1692 'code' => 'copyuploaddisabled',
1693 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1695 'copyuploadbaddomain' => array(
1696 'code' => 'copyuploadbaddomain',
1697 'info' => 'Uploads by URL are not allowed from this domain.'
1699 'copyuploadbadurl' => array(
1700 'code' => 'copyuploadbadurl',
1701 'info' => 'Upload not allowed from this URL.'
1704 'filename-tooshort' => array(
1705 'code' => 'filename-tooshort',
1706 'info' => 'The filename is too short'
1708 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1709 'illegal-filename' => array(
1710 'code' => 'illegal-filename',
1711 'info' => 'The filename is not allowed'
1713 'filetype-missing' => array(
1714 'code' => 'filetype-missing',
1715 'info' => 'The file is missing an extension'
1718 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1720 // @codingStandardsIgnoreEnd
1723 * Helper function for readonly errors
1725 public function dieReadOnly() {
1726 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1727 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1728 array( 'readonlyreason' => wfReadOnlyReason() ) );
1732 * Output the error message related to a certain array
1733 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1735 public function dieUsageMsg( $error ) {
1736 # most of the time we send a 1 element, so we might as well send it as
1737 # a string and make this an array here.
1738 if ( is_string( $error ) ) {
1739 $error = array( $error );
1741 $parsed = $this->parseMsg( $error );
1742 $this->dieUsage( $parsed['info'], $parsed['code'] );
1746 * Will only set a warning instead of failing if the global $wgDebugAPI
1747 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1748 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1751 public function dieUsageMsgOrDebug( $error ) {
1752 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1753 $this->dieUsageMsg( $error );
1756 if ( is_string( $error ) ) {
1757 $error = array( $error );
1759 $parsed = $this->parseMsg( $error );
1760 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1764 * Die with the $prefix.'badcontinue' error. This call is common enough to
1765 * make it into the base method.
1766 * @param bool $condition Will only die if this value is true
1769 protected function dieContinueUsageIf( $condition ) {
1772 'Invalid continue param. You should pass the original value returned by the previous query',
1778 * Return the error message related to a certain array
1779 * @param array $error Element of a getUserPermissionsErrors()-style array
1780 * @return array('code' => code, 'info' => info)
1782 public function parseMsg( $error ) {
1783 $error = (array)$error; // It seems strings sometimes make their way in here
1784 $key = array_shift( $error );
1786 // Check whether the error array was nested
1787 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1788 if ( is_array( $key ) ) {
1790 $key = array_shift( $error );
1793 if ( isset( self
::$messageMap[$key] ) ) {
1795 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1796 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1800 // If the key isn't present, throw an "unknown error"
1801 return $this->parseMsg( array( 'unknownerror', $key ) );
1805 * Internal code errors should be reported with this method
1806 * @param string $method Method or function name
1807 * @param string $message Error message
1808 * @throws MWException
1810 protected static function dieDebug( $method, $message ) {
1811 throw new MWException( "Internal error in $method: $message" );
1816 /************************************************************************//**
1817 * @name Help message generation
1822 * Generates help message for this module, or false if there is no description
1823 * @return string|bool
1825 public function makeHelpMsg() {
1826 static $lnPrfx = "\n ";
1828 $msg = $this->getFinalDescription();
1830 if ( $msg !== false ) {
1832 if ( !is_array( $msg ) ) {
1837 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
1839 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
1841 if ( $this->isReadMode() ) {
1842 $msg .= "\nThis module requires read rights";
1844 if ( $this->isWriteMode() ) {
1845 $msg .= "\nThis module requires write rights";
1847 if ( $this->mustBePosted() ) {
1848 $msg .= "\nThis module only accepts POST requests";
1850 if ( $this->isReadMode() ||
$this->isWriteMode() ||
1851 $this->mustBePosted()
1857 $paramsMsg = $this->makeHelpMsgParameters();
1858 if ( $paramsMsg !== false ) {
1859 $msg .= "Parameters:\n$paramsMsg";
1862 $examples = $this->getExamples();
1864 if ( !is_array( $examples ) ) {
1869 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
1870 foreach ( $examples as $k => $v ) {
1871 if ( is_numeric( $k ) ) {
1874 if ( is_array( $v ) ) {
1875 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
1877 $msgExample = " $v";
1880 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
1890 * @param string $item
1893 private function indentExampleText( $item ) {
1898 * @param string $prefix Text to split output items
1899 * @param string $title What is being output
1900 * @param string|array $input
1903 protected function makeHelpArrayToString( $prefix, $title, $input ) {
1904 if ( $input === false ) {
1907 if ( !is_array( $input ) ) {
1908 $input = array( $input );
1911 if ( count( $input ) > 0 ) {
1913 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
1917 $msg .= implode( $prefix, $input ) . "\n";
1926 * Generates the parameter descriptions for this module, to be displayed in the
1928 * @return string|bool
1930 public function makeHelpMsgParameters() {
1931 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
1934 $paramsDescription = $this->getFinalParamDescription();
1936 $paramPrefix = "\n" . str_repeat( ' ', 24 );
1937 $descWordwrap = "\n" . str_repeat( ' ', 28 );
1938 foreach ( $params as $paramName => $paramSettings ) {
1939 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
1940 if ( is_array( $desc ) ) {
1941 $desc = implode( $paramPrefix, $desc );
1945 if ( !is_array( $paramSettings ) ) {
1946 $paramSettings = array(
1947 self
::PARAM_DFLT
=> $paramSettings,
1951 //handle missing type
1952 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
1953 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
1954 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
1956 if ( is_bool( $dflt ) ) {
1957 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
1958 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
1959 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
1960 } elseif ( is_int( $dflt ) ) {
1961 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
1965 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1966 && $paramSettings[self
::PARAM_DEPRECATED
]
1968 $desc = "DEPRECATED! $desc";
1971 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
1972 && $paramSettings[self
::PARAM_REQUIRED
]
1974 $desc .= $paramPrefix . "This parameter is required";
1977 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1978 ?
$paramSettings[self
::PARAM_TYPE
]
1980 if ( isset( $type ) ) {
1981 $hintPipeSeparated = true;
1982 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1983 ?
$paramSettings[self
::PARAM_ISMULTI
]
1986 $prompt = 'Values (separate with \'|\'): ';
1988 $prompt = 'One value: ';
1991 if ( $type === 'submodule' ) {
1992 $type = $this->getModuleManager()->getNames( $paramName );
1995 if ( is_array( $type ) ) {
1997 $nothingPrompt = '';
1998 foreach ( $type as $t ) {
2000 $nothingPrompt = 'Can be empty, or ';
2005 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2006 $choicesstring = implode( ', ', $choices );
2007 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2008 $hintPipeSeparated = false;
2012 // Special handling because namespaces are
2013 // type-limited, yet they are not given
2014 $desc .= $paramPrefix . $prompt;
2015 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
2016 100, $descWordwrap );
2017 $hintPipeSeparated = false;
2020 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2021 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
2022 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2024 $desc .= ' allowed';
2027 $s = $multi ?
's' : '';
2028 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
2029 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
2030 if ( $hasMin ||
$hasMax ) {
2032 $intRangeStr = "The value$s must be no less than " .
2033 "{$paramSettings[self::PARAM_MIN]}";
2034 } elseif ( !$hasMin ) {
2035 $intRangeStr = "The value$s must be no more than " .
2036 "{$paramSettings[self::PARAM_MAX]}";
2038 $intRangeStr = "The value$s must be between " .
2039 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2042 $desc .= $paramPrefix . $intRangeStr;
2046 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2052 if ( $hintPipeSeparated ) {
2053 $desc .= $paramPrefix . "Separate values with '|'";
2056 $isArray = is_array( $type );
2058 ||
$isArray && count( $type ) > self
::LIMIT_SML1
2060 $desc .= $paramPrefix . "Maximum number of values " .
2061 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
2066 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
2067 if ( !is_null( $default ) && $default !== false ) {
2068 $desc .= $paramPrefix . "Default: $default";
2071 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2082 /************************************************************************//**
2088 * Profiling: total module execution time
2090 private $mTimeIn = 0, $mModuleTime = 0;
2093 * Get the name of the module as shown in the profiler log
2095 * @param DatabaseBase|bool $db
2099 public function getModuleProfileName( $db = false ) {
2101 return 'API:' . $this->mModuleName
. '-DB';
2104 return 'API:' . $this->mModuleName
;
2108 * Start module profiling
2110 public function profileIn() {
2111 if ( $this->mTimeIn
!== 0 ) {
2112 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2114 $this->mTimeIn
= microtime( true );
2115 wfProfileIn( $this->getModuleProfileName() );
2119 * End module profiling
2121 public function profileOut() {
2122 if ( $this->mTimeIn
=== 0 ) {
2123 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2125 if ( $this->mDBTimeIn
!== 0 ) {
2128 'Must be called after database profiling is done with profileDBOut()'
2132 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2134 wfProfileOut( $this->getModuleProfileName() );
2138 * When modules crash, sometimes it is needed to do a profileOut() regardless
2139 * of the profiling state the module was in. This method does such cleanup.
2141 public function safeProfileOut() {
2142 if ( $this->mTimeIn
!== 0 ) {
2143 if ( $this->mDBTimeIn
!== 0 ) {
2144 $this->profileDBOut();
2146 $this->profileOut();
2151 * Total time the module was executed
2154 public function getProfileTime() {
2155 if ( $this->mTimeIn
!== 0 ) {
2156 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2159 return $this->mModuleTime
;
2163 * Profiling: database execution time
2165 private $mDBTimeIn = 0, $mDBTime = 0;
2168 * Start module profiling
2170 public function profileDBIn() {
2171 if ( $this->mTimeIn
=== 0 ) {
2174 'Must be called while profiling the entire module with profileIn()'
2177 if ( $this->mDBTimeIn
!== 0 ) {
2178 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2180 $this->mDBTimeIn
= microtime( true );
2181 wfProfileIn( $this->getModuleProfileName( true ) );
2185 * End database profiling
2187 public function profileDBOut() {
2188 if ( $this->mTimeIn
=== 0 ) {
2189 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2190 'the entire module with profileIn()' );
2192 if ( $this->mDBTimeIn
=== 0 ) {
2193 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2196 $time = microtime( true ) - $this->mDBTimeIn
;
2197 $this->mDBTimeIn
= 0;
2199 $this->mDBTime +
= $time;
2200 $this->getMain()->mDBTime +
= $time;
2201 wfProfileOut( $this->getModuleProfileName( true ) );
2205 * Total time the module used the database
2208 public function getProfileDBTime() {
2209 if ( $this->mDBTimeIn
!== 0 ) {
2210 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2213 return $this->mDBTime
;
2217 * Write logging information for API features to a debug log, for usage
2219 * @param string $feature Feature being used.
2221 protected function logFeatureUsage( $feature ) {
2222 $request = $this->getRequest();
2223 $s = '"' . addslashes( $feature ) . '"' .
2224 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2225 ' "' . $request->getIP() . '"' .
2226 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2227 ' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"';
2228 wfDebugLog( 'api-feature-usage', $s, 'private' );
2233 /************************************************************************//**
2238 /// @deprecated since 1.24
2239 const PROP_ROOT
= 'ROOT';
2240 /// @deprecated since 1.24
2241 const PROP_LIST
= 'LIST';
2242 /// @deprecated since 1.24
2243 const PROP_TYPE
= 0;
2244 /// @deprecated since 1.24
2245 const PROP_NULLABLE
= 1;
2248 * Formerly returned a string that identifies the version of the extending
2249 * class. Typically included the class name, the svn revision, timestamp,
2250 * and last author. Usually done with SVN's Id keyword
2252 * @deprecated since 1.21, version string is no longer supported
2255 public function getVersion() {
2256 wfDeprecated( __METHOD__
, '1.21' );
2261 * Formerly used to fetch a list of possible properites in the result,
2262 * somehow organized with respect to the prop parameter that causes them to
2263 * be returned. The specific semantics of the return value was never
2264 * specified. Since this was never possible to be accurately updated, it
2267 * @deprecated since 1.24
2268 * @return array|bool
2270 protected function getResultProperties() {
2271 wfDeprecated( __METHOD__
, '1.24' );
2276 * @see self::getResultProperties()
2277 * @deprecated since 1.24
2278 * @return array|bool
2280 public function getFinalResultProperties() {
2281 wfDeprecated( __METHOD__
, '1.24' );
2286 * @see self::getResultProperties()
2287 * @deprecated since 1.24
2289 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2290 wfDeprecated( __METHOD__
, '1.24' );
2294 * @see self::getPossibleErrors()
2295 * @deprecated since 1.24
2298 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2299 wfDeprecated( __METHOD__
, '1.24' );
2304 * @see self::getPossibleErrors()
2305 * @deprecated since 1.24
2308 public function getRequireMaxOneParameterErrorMessages( $params ) {
2309 wfDeprecated( __METHOD__
, '1.24' );
2314 * @see self::getPossibleErrors()
2315 * @deprecated since 1.24
2318 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2319 wfDeprecated( __METHOD__
, '1.24' );
2324 * @see self::getPossibleErrors()
2325 * @deprecated since 1.24
2328 public function getTitleOrPageIdErrorMessage() {
2329 wfDeprecated( __METHOD__
, '1.24' );
2334 * This formerly attempted to return a list of all possible errors returned
2335 * by the module. However, this was impossible to maintain in many cases
2336 * since errors could come from other areas of MediaWiki and in some cases
2337 * from arbitrary extension hooks. Since a partial list claiming to be
2338 * comprehensive is unlikely to be useful, it was removed.
2340 * @deprecated since 1.24
2343 public function getPossibleErrors() {
2344 wfDeprecated( __METHOD__
, '1.24' );
2349 * @see self::getPossibleErrors()
2350 * @deprecated since 1.24
2353 public function getFinalPossibleErrors() {
2354 wfDeprecated( __METHOD__
, '1.24' );
2359 * @see self::getPossibleErrors()
2360 * @deprecated since 1.24
2363 public function parseErrors( $errors ) {
2364 wfDeprecated( __METHOD__
, '1.24' );
2372 * For really cool vim folding this needs to be at the end:
2373 * vim: foldmarker=@{,@} foldmethod=marker