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 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT
= 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST
= 'LIST';
74 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE
= 1;
78 const LIMIT_BIG1
= 500; // Fast query, std user limit
79 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1
= 50; // Slow query, std user limit
81 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
88 const GET_VALUES_FOR_HELP
= 1;
93 private $mModuleName, $mModulePrefix;
94 private $mSlaveDB = null;
95 private $mParamCache = array();
98 * @param ApiMain $mainModule
99 * @param string $moduleName Name of this module
100 * @param string $modulePrefix Prefix to use for parameter names
102 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
103 $this->mMainModule
= $mainModule;
104 $this->mModuleName
= $moduleName;
105 $this->mModulePrefix
= $modulePrefix;
107 if ( !$this->isMain() ) {
108 $this->setContext( $mainModule->getContext() );
112 /*****************************************************************************
114 *****************************************************************************/
117 * Evaluates the parameters, performs the requested query, and sets up
118 * the result. Concrete implementations of ApiBase must override this
119 * method to provide whatever functionality their module offers.
120 * Implementations must not produce any output on their own and are not
121 * expected to handle any errors.
123 * The execute() method will be invoked directly by ApiMain immediately
124 * before the result of the module is output. Aside from the
125 * constructor, implementations should assume that no other methods
126 * will be called externally on the module before the result is
129 * The result data should be stored in the ApiResult object available
130 * through getResult().
132 abstract public function execute();
135 * Returns a string that identifies the version of the extending class.
136 * Typically includes the class name, the svn revision, timestamp, and
137 * last author. Usually done with SVN's Id keyword
139 * @deprecated since 1.21, version string is no longer supported
141 public function getVersion() {
142 wfDeprecated( __METHOD__
, '1.21' );
148 * Get the name of the module being executed by this instance
151 public function getModuleName() {
152 return $this->mModuleName
;
156 * Get the module manager, or null if this module has no sub-modules
158 * @return ApiModuleManager
160 public function getModuleManager() {
165 * Get parameter prefix (usually two letters or an empty string).
168 public function getModulePrefix() {
169 return $this->mModulePrefix
;
173 * Get the name of the module as shown in the profiler log
175 * @param DatabaseBase|bool $db
179 public function getModuleProfileName( $db = false ) {
181 return 'API:' . $this->mModuleName
. '-DB';
184 return 'API:' . $this->mModuleName
;
188 * Get the main module
191 public function getMain() {
192 return $this->mMainModule
;
196 * Returns true if this module is the main module ($this === $this->mMainModule),
200 public function isMain() {
201 return $this === $this->mMainModule
;
205 * Get the result object
208 public function getResult() {
209 // Main module has getResult() method overridden
210 // Safety - avoid infinite loop:
211 if ( $this->isMain() ) {
212 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
215 return $this->getMain()->getResult();
219 * Get the result data array (read-only)
222 public function getResultData() {
223 return $this->getResult()->getData();
227 * Set warning section for this module. Users should monitor this
228 * section to notice any changes in API. Multiple calls to this
229 * function will result in the warning messages being separated by
231 * @param string $warning Warning message
233 public function setWarning( $warning ) {
234 $result = $this->getResult();
235 $data = $result->getData();
236 $moduleName = $this->getModuleName();
237 if ( isset( $data['warnings'][$moduleName] ) ) {
238 // Don't add duplicate warnings
239 $oldWarning = $data['warnings'][$moduleName]['*'];
240 $warnPos = strpos( $oldWarning, $warning );
241 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
242 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
243 // Check if $warning is followed by "\n" or the end of the $oldWarning
244 $warnPos +
= strlen( $warning );
245 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
249 // If there is a warning already, append it to the existing one
250 $warning = "$oldWarning\n$warning";
253 ApiResult
::setContent( $msg, $warning );
254 $result->addValue( 'warnings', $moduleName,
255 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
259 * If the module may only be used with a certain format module,
260 * it should override this method to return an instance of that formatter.
261 * A value of null means the default format will be used.
262 * @return mixed Instance of a derived class of ApiFormatBase, or null
264 public function getCustomPrinter() {
269 * Generates help message for this module, or false if there is no description
270 * @return string|bool
272 public function makeHelpMsg() {
273 static $lnPrfx = "\n ";
275 $msg = $this->getFinalDescription();
277 if ( $msg !== false ) {
279 if ( !is_array( $msg ) ) {
284 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
286 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
288 if ( $this->isReadMode() ) {
289 $msg .= "\nThis module requires read rights";
291 if ( $this->isWriteMode() ) {
292 $msg .= "\nThis module requires write rights";
294 if ( $this->mustBePosted() ) {
295 $msg .= "\nThis module only accepts POST requests";
297 if ( $this->isReadMode() ||
$this->isWriteMode() ||
298 $this->mustBePosted()
304 $paramsMsg = $this->makeHelpMsgParameters();
305 if ( $paramsMsg !== false ) {
306 $msg .= "Parameters:\n$paramsMsg";
309 $examples = $this->getExamples();
311 if ( !is_array( $examples ) ) {
316 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
317 foreach ( $examples as $k => $v ) {
318 if ( is_numeric( $k ) ) {
321 if ( is_array( $v ) ) {
322 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
327 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
337 * @param string $item
340 private function indentExampleText( $item ) {
345 * @param string $prefix Text to split output items
346 * @param string $title What is being output
347 * @param string|array $input
350 protected function makeHelpArrayToString( $prefix, $title, $input ) {
351 if ( $input === false ) {
354 if ( !is_array( $input ) ) {
355 $input = array( $input );
358 if ( count( $input ) > 0 ) {
360 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
364 $msg .= implode( $prefix, $input ) . "\n";
373 * Generates the parameter descriptions for this module, to be displayed in the
375 * @return string|bool
377 public function makeHelpMsgParameters() {
378 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
381 $paramsDescription = $this->getFinalParamDescription();
383 $paramPrefix = "\n" . str_repeat( ' ', 24 );
384 $descWordwrap = "\n" . str_repeat( ' ', 28 );
385 foreach ( $params as $paramName => $paramSettings ) {
386 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
387 if ( is_array( $desc ) ) {
388 $desc = implode( $paramPrefix, $desc );
392 if ( !is_array( $paramSettings ) ) {
393 $paramSettings = array(
394 self
::PARAM_DFLT
=> $paramSettings,
398 //handle missing type
399 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
400 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
401 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
403 if ( is_bool( $dflt ) ) {
404 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
405 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
406 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
407 } elseif ( is_int( $dflt ) ) {
408 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
412 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
413 && $paramSettings[self
::PARAM_DEPRECATED
]
415 $desc = "DEPRECATED! $desc";
418 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
419 && $paramSettings[self
::PARAM_REQUIRED
]
421 $desc .= $paramPrefix . "This parameter is required";
424 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
425 ?
$paramSettings[self
::PARAM_TYPE
]
427 if ( isset( $type ) ) {
428 $hintPipeSeparated = true;
429 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
430 ?
$paramSettings[self
::PARAM_ISMULTI
]
433 $prompt = 'Values (separate with \'|\'): ';
435 $prompt = 'One value: ';
438 if ( is_array( $type ) ) {
441 foreach ( $type as $t ) {
443 $nothingPrompt = 'Can be empty, or ';
448 $desc .= $paramPrefix . $nothingPrompt . $prompt;
449 $choicesstring = implode( ', ', $choices );
450 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
451 $hintPipeSeparated = false;
455 // Special handling because namespaces are
456 // type-limited, yet they are not given
457 $desc .= $paramPrefix . $prompt;
458 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
459 100, $descWordwrap );
460 $hintPipeSeparated = false;
463 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
464 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
465 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
470 $s = $multi ?
's' : '';
471 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
472 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
473 if ( $hasMin ||
$hasMax ) {
475 $intRangeStr = "The value$s must be no less than " .
476 "{$paramSettings[self::PARAM_MIN]}";
477 } elseif ( !$hasMin ) {
478 $intRangeStr = "The value$s must be no more than " .
479 "{$paramSettings[self::PARAM_MAX]}";
481 $intRangeStr = "The value$s must be between " .
482 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
485 $desc .= $paramPrefix . $intRangeStr;
489 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
495 if ( $hintPipeSeparated ) {
496 $desc .= $paramPrefix . "Separate values with '|'";
499 $isArray = is_array( $type );
501 ||
$isArray && count( $type ) > self
::LIMIT_SML1
503 $desc .= $paramPrefix . "Maximum number of values " .
504 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
509 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
510 if ( !is_null( $default ) && $default !== false ) {
511 $desc .= $paramPrefix . "Default: $default";
514 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
524 * Returns the description string for this module
525 * @return string|array
527 protected function getDescription() {
532 * Returns usage examples for this module. Return false if no examples are available.
533 * @return bool|string|array
535 protected function getExamples() {
540 * Returns an array of allowed parameters (parameter name) => (default
541 * value) or (parameter name) => (array with PARAM_* constants as keys)
542 * Don't call this function directly: use getFinalParams() to allow
543 * hooks to modify parameters as needed.
545 * Some derived classes may choose to handle an integer $flags parameter
546 * in the overriding methods. Callers of this method can pass zero or
547 * more OR-ed flags like GET_VALUES_FOR_HELP.
551 protected function getAllowedParams( /* $flags = 0 */ ) {
552 // int $flags is not declared because it causes "Strict standards"
553 // warning. Most derived classes do not implement it.
558 * Returns an array of parameter descriptions.
559 * Don't call this function directly: use getFinalParamDescription() to
560 * allow hooks to modify descriptions as needed.
561 * @return array|bool False on no parameter descriptions
563 protected function getParamDescription() {
568 * Get final list of parameters, after hooks have had a chance to
569 * tweak it as needed.
571 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
572 * @return array|bool False on no parameters
573 * @since 1.21 $flags param added
575 public function getFinalParams( $flags = 0 ) {
576 $params = $this->getAllowedParams( $flags );
577 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
583 * Get final parameter descriptions, after hooks have had a chance to tweak it as
586 * @return array|bool False on no parameter descriptions
588 public function getFinalParamDescription() {
589 $desc = $this->getParamDescription();
590 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
596 * Formerly used to fetch a list of possible properites in the result,
597 * somehow organized with respect to the prop parameter that causes them to
598 * be returned. The specific semantics of the return value was never
599 * specified. Since this was never possible to be accurately updated, it
602 * @deprecated since 1.24
605 protected function getResultProperties() {
606 wfDeprecated( __METHOD__
, '1.24' );
611 * @see self::getResultProperties()
612 * @deprecated since 1.24
615 public function getFinalResultProperties() {
616 wfDeprecated( __METHOD__
, '1.24' );
621 * @see self::getResultProperties()
622 * @deprecated since 1.24
624 protected static function addTokenProperties( &$props, $tokenFunctions ) {
625 wfDeprecated( __METHOD__
, '1.24' );
629 * Get final module description, after hooks have had a chance to tweak it as
632 * @return array|bool False on no parameters
634 public function getFinalDescription() {
635 $desc = $this->getDescription();
636 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
642 * This method mangles parameter name based on the prefix supplied to the constructor.
643 * Override this method to change parameter name during runtime
644 * @param string $paramName Parameter name
645 * @return string Prefixed parameter name
647 public function encodeParamName( $paramName ) {
648 return $this->mModulePrefix
. $paramName;
652 * Using getAllowedParams(), this function makes an array of the values
653 * provided by the user, with key being the name of the variable, and
654 * value - validated value from user or default. limits will not be
655 * parsed if $parseLimit is set to false; use this when the max
656 * limit is not definitive yet, e.g. when getting revisions.
657 * @param bool $parseLimit True by default
660 public function extractRequestParams( $parseLimit = true ) {
661 // Cache parameters, for performance and to avoid bug 24564.
662 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
663 $params = $this->getFinalParams();
666 if ( $params ) { // getFinalParams() can return false
667 foreach ( $params as $paramName => $paramSettings ) {
668 $results[$paramName] = $this->getParameterFromSettings(
669 $paramName, $paramSettings, $parseLimit );
672 $this->mParamCache
[$parseLimit] = $results;
675 return $this->mParamCache
[$parseLimit];
679 * Get a value for the given parameter
680 * @param string $paramName Parameter name
681 * @param bool $parseLimit See extractRequestParams()
682 * @return mixed Parameter value
684 protected function getParameter( $paramName, $parseLimit = true ) {
685 $params = $this->getFinalParams();
686 $paramSettings = $params[$paramName];
688 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
692 * Die if none or more than one of a certain set of parameters is set and not false.
694 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
695 * @param string $required,... Names of parameters of which exactly one must be set
697 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
698 $required = func_get_args();
699 array_shift( $required );
700 $p = $this->getModulePrefix();
702 $intersection = array_intersect( array_keys( array_filter( $params,
703 array( $this, "parameterNotEmpty" ) ) ), $required );
705 if ( count( $intersection ) > 1 ) {
707 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
709 } elseif ( count( $intersection ) == 0 ) {
711 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
718 * @see self::getPossibleErrors()
719 * @deprecated since 1.24
722 public function getRequireOnlyOneParameterErrorMessages( $params ) {
723 wfDeprecated( __METHOD__
, '1.24' );
728 * Die if more than one of a certain set of parameters is set and not false.
730 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
731 * @param string $required,... Names of parameters of which at most one must be set
733 public function requireMaxOneParameter( $params, $required /*...*/ ) {
734 $required = func_get_args();
735 array_shift( $required );
736 $p = $this->getModulePrefix();
738 $intersection = array_intersect( array_keys( array_filter( $params,
739 array( $this, "parameterNotEmpty" ) ) ), $required );
741 if ( count( $intersection ) > 1 ) {
743 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
750 * @see self::getPossibleErrors()
751 * @deprecated since 1.24
754 public function getRequireMaxOneParameterErrorMessages( $params ) {
755 wfDeprecated( __METHOD__
, '1.24' );
760 * Die if none of a certain set of parameters is set and not false.
763 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
764 * @param string $required,... Names of parameters of which at least one must be set
766 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
767 $required = func_get_args();
768 array_shift( $required );
769 $p = $this->getModulePrefix();
771 $intersection = array_intersect(
772 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
776 if ( count( $intersection ) == 0 ) {
777 $this->dieUsage( "At least one of the parameters {$p}" .
778 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
783 * @see self::getPossibleErrors()
784 * @deprecated since 1.24
787 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
788 wfDeprecated( __METHOD__
, '1.24' );
793 * Get a WikiPage object from a title or pageid param, if possible.
794 * Can die, if no param is set or if the title or page id is not valid.
796 * @param array $params
797 * @param bool|string $load Whether load the object's state from the database:
798 * - false: don't load (if the pageid is given, it will still be loaded)
799 * - 'fromdb': load from a slave database
800 * - 'fromdbmaster': load from the master database
803 public function getTitleOrPageId( $params, $load = false ) {
804 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
807 if ( isset( $params['title'] ) ) {
808 $titleObj = Title
::newFromText( $params['title'] );
809 if ( !$titleObj ||
$titleObj->isExternal() ) {
810 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
812 if ( !$titleObj->canExist() ) {
813 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
815 $pageObj = WikiPage
::factory( $titleObj );
816 if ( $load !== false ) {
817 $pageObj->loadPageData( $load );
819 } elseif ( isset( $params['pageid'] ) ) {
820 if ( $load === false ) {
823 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
825 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
833 * @see self::getPossibleErrors()
834 * @deprecated since 1.24
837 public function getTitleOrPageIdErrorMessage() {
838 wfDeprecated( __METHOD__
, '1.24' );
843 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
845 * @param object $x Parameter to check is not null/false
848 private function parameterNotEmpty( $x ) {
849 return !is_null( $x ) && $x !== false;
853 * Return true if we're to watch the page, false if not, null if no change.
854 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
855 * @param Title $titleObj The page under consideration
856 * @param string $userOption The user option to consider when $watchlist=preferences.
857 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
860 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
862 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
864 switch ( $watchlist ) {
872 # If the user is already watching, don't bother checking
873 if ( $userWatching ) {
876 # If no user option was passed, use watchdefault and watchcreations
877 if ( is_null( $userOption ) ) {
878 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
879 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
882 # Watch the article based on the user preference
883 return $this->getUser()->getBoolOption( $userOption );
886 return $userWatching;
889 return $userWatching;
894 * Set a watch (or unwatch) based the based on a watchlist parameter.
895 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
896 * @param Title $titleObj The article's title to change
897 * @param string $userOption The user option to consider when $watch=preferences
899 protected function setWatch( $watch, $titleObj, $userOption = null ) {
900 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
901 if ( $value === null ) {
905 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
909 * Using the settings determine the value for the given parameter
911 * @param string $paramName Parameter name
912 * @param array|mixed $paramSettings Default value or an array of settings
913 * using PARAM_* constants.
914 * @param bool $parseLimit Parse limit?
915 * @return mixed Parameter value
917 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
918 // Some classes may decide to change parameter names
919 $encParamName = $this->encodeParamName( $paramName );
921 if ( !is_array( $paramSettings ) ) {
922 $default = $paramSettings;
924 $type = gettype( $paramSettings );
929 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
930 ?
$paramSettings[self
::PARAM_DFLT
]
932 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
933 ?
$paramSettings[self
::PARAM_ISMULTI
]
935 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
936 ?
$paramSettings[self
::PARAM_TYPE
]
938 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
939 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
941 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
942 ?
$paramSettings[self
::PARAM_DEPRECATED
]
944 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
945 ?
$paramSettings[self
::PARAM_REQUIRED
]
948 // When type is not given, and no choices, the type is the same as $default
949 if ( !isset( $type ) ) {
950 if ( isset( $default ) ) {
951 $type = gettype( $default );
953 $type = 'NULL'; // allow everything
958 if ( $type == 'boolean' ) {
959 if ( isset( $default ) && $default !== false ) {
960 // Having a default value of anything other than 'false' is not allowed
963 "Boolean param $encParamName's default is set to '$default'. " .
964 "Boolean parameters must default to false."
968 $value = $this->getMain()->getCheck( $encParamName );
969 } elseif ( $type == 'upload' ) {
970 if ( isset( $default ) ) {
971 // Having a default value is not allowed
974 "File upload param $encParamName's default is set to " .
975 "'$default'. File upload parameters may not have a default." );
978 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
980 $value = $this->getMain()->getUpload( $encParamName );
981 if ( !$value->exists() ) {
982 // This will get the value without trying to normalize it
983 // (because trying to normalize a large binary file
984 // accidentally uploaded as a field fails spectacularly)
985 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
986 if ( $value !== null ) {
988 "File upload param $encParamName is not a file upload; " .
989 "be sure to use multipart/form-data for your POST and include " .
990 "a filename in the Content-Disposition header.",
991 "badupload_{$encParamName}"
996 $value = $this->getMain()->getVal( $encParamName, $default );
998 if ( isset( $value ) && $type == 'namespace' ) {
999 $type = MWNamespace
::getValidNamespaces();
1003 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1004 $value = $this->parseMultiValue(
1008 is_array( $type ) ?
$type : null
1012 // More validation only when choices were not given
1013 // choices were validated in parseMultiValue()
1014 if ( isset( $value ) ) {
1015 if ( !is_array( $type ) ) {
1017 case 'NULL': // nothing to do
1020 if ( $required && $value === '' ) {
1021 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1024 case 'integer': // Force everything using intval() and optionally validate limits
1025 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1026 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1027 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1028 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1030 if ( is_array( $value ) ) {
1031 $value = array_map( 'intval', $value );
1032 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1033 foreach ( $value as &$v ) {
1034 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1038 $value = intval( $value );
1039 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1040 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1045 if ( !$parseLimit ) {
1046 // Don't do any validation whatsoever
1049 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1050 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1054 "MAX1 or MAX2 are not defined for the limit $encParamName"
1058 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1060 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1061 if ( $value == 'max' ) {
1062 $value = $this->getMain()->canApiHighLimits()
1063 ?
$paramSettings[self
::PARAM_MAX2
]
1064 : $paramSettings[self
::PARAM_MAX
];
1065 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1067 $value = intval( $value );
1068 $this->validateLimit(
1072 $paramSettings[self
::PARAM_MAX
],
1073 $paramSettings[self
::PARAM_MAX2
]
1079 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1083 if ( is_array( $value ) ) {
1084 foreach ( $value as $key => $val ) {
1085 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1088 $value = $this->validateTimestamp( $value, $encParamName );
1092 if ( is_array( $value ) ) {
1093 foreach ( $value as $key => $val ) {
1094 $value[$key] = $this->validateUser( $val, $encParamName );
1097 $value = $this->validateUser( $value, $encParamName );
1100 case 'upload': // nothing to do
1103 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1107 // Throw out duplicates if requested
1108 if ( !$dupes && is_array( $value ) ) {
1109 $value = array_unique( $value );
1112 // Set a warning if a deprecated parameter has been passed
1113 if ( $deprecated && $value !== false ) {
1114 $this->setWarning( "The $encParamName parameter has been deprecated." );
1116 } elseif ( $required ) {
1117 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1124 * Return an array of values that were given in a 'a|b|c' notation,
1125 * after it optionally validates them against the list allowed values.
1127 * @param string $valueName The name of the parameter (for error
1129 * @param mixed $value The value being parsed
1130 * @param bool $allowMultiple Can $value contain more than one value
1132 * @param string[]|null $allowedValues An array of values to check against. If
1133 * null, all values are accepted.
1134 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1136 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1137 if ( trim( $value ) === '' && $allowMultiple ) {
1141 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1142 // because it unstubs $wgUser
1143 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1144 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1148 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1149 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1150 "the limit is $sizeLimit" );
1153 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1154 // Bug 33482 - Allow entries with | in them for non-multiple values
1155 if ( in_array( $value, $allowedValues, true ) ) {
1159 $possibleValues = is_array( $allowedValues )
1160 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1163 "Only one $possibleValues is allowed for parameter '$valueName'",
1164 "multival_$valueName"
1168 if ( is_array( $allowedValues ) ) {
1169 // Check for unknown values
1170 $unknown = array_diff( $valuesList, $allowedValues );
1171 if ( count( $unknown ) ) {
1172 if ( $allowMultiple ) {
1173 $s = count( $unknown ) > 1 ?
's' : '';
1174 $vals = implode( ", ", $unknown );
1175 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1178 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1179 "unknown_$valueName"
1183 // Now throw them out
1184 $valuesList = array_intersect( $valuesList, $allowedValues );
1187 return $allowMultiple ?
$valuesList : $valuesList[0];
1191 * Validate the value against the minimum and user/bot maximum limits.
1192 * Prints usage info on failure.
1193 * @param string $paramName Parameter name
1194 * @param int $value Parameter value
1195 * @param int|null $min Minimum value
1196 * @param int|null $max Maximum value for users
1197 * @param int $botMax Maximum value for sysops/bots
1198 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1200 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1201 if ( !is_null( $min ) && $value < $min ) {
1203 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1204 $this->warnOrDie( $msg, $enforceLimits );
1208 // Minimum is always validated, whereas maximum is checked only if not
1209 // running in internal call mode
1210 if ( $this->getMain()->isInternalMode() ) {
1214 // Optimization: do not check user's bot status unless really needed -- skips db query
1215 // assumes $botMax >= $max
1216 if ( !is_null( $max ) && $value > $max ) {
1217 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1218 if ( $value > $botMax ) {
1219 $msg = $this->encodeParamName( $paramName ) .
1220 " may not be over $botMax (set to $value) for bots or sysops";
1221 $this->warnOrDie( $msg, $enforceLimits );
1225 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1226 $this->warnOrDie( $msg, $enforceLimits );
1233 * Validate and normalize of parameters of type 'timestamp'
1234 * @param string $value Parameter value
1235 * @param string $encParamName Parameter name
1236 * @return string Validated and normalized parameter
1238 function validateTimestamp( $value, $encParamName ) {
1239 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1240 if ( $unixTimestamp === false ) {
1242 "Invalid value '$value' for timestamp parameter $encParamName",
1243 "badtimestamp_{$encParamName}"
1247 return wfTimestamp( TS_MW
, $unixTimestamp );
1251 * Validate and normalize of parameters of type 'user'
1252 * @param string $value Parameter value
1253 * @param string $encParamName Parameter name
1254 * @return string Validated and normalized parameter
1256 private function validateUser( $value, $encParamName ) {
1257 $title = Title
::makeTitleSafe( NS_USER
, $value );
1258 if ( $title === null ) {
1260 "Invalid value '$value' for user parameter $encParamName",
1261 "baduser_{$encParamName}"
1265 return $title->getText();
1269 * Adds a warning to the output, else dies
1271 * @param string $msg Message to show as a warning, or error message if dying
1272 * @param bool $enforceLimits Whether this is an enforce (die)
1274 private function warnOrDie( $msg, $enforceLimits = false ) {
1275 if ( $enforceLimits ) {
1276 $this->dieUsage( $msg, 'integeroutofrange' );
1279 $this->setWarning( $msg );
1283 * Truncate an array to a certain length.
1284 * @param array $arr Array to truncate
1285 * @param int $limit Maximum length
1286 * @return bool True if the array was truncated, false otherwise
1288 public static function truncateArray( &$arr, $limit ) {
1290 while ( count( $arr ) > $limit ) {
1299 * Throw a UsageException, which will (if uncaught) call the main module's
1300 * error handler and die with an error message.
1302 * @param string $description One-line human-readable description of the
1303 * error condition, e.g., "The API requires a valid action parameter"
1304 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1305 * automated identification of the error, e.g., 'unknown_action'
1306 * @param int $httpRespCode HTTP response code
1307 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1308 * @throws UsageException
1310 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1311 Profiler
::instance()->close();
1312 throw new UsageException(
1314 $this->encodeParamName( $errorCode ),
1321 * Get error (as code, string) from a Status object.
1324 * @param Status $status
1325 * @return array Array of code and error string
1327 public function getErrorFromStatus( $status ) {
1328 if ( $status->isGood() ) {
1329 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1332 $errors = $status->getErrorsArray();
1334 // No errors? Assume the warnings should be treated as errors
1335 $errors = $status->getWarningsArray();
1338 // Still no errors? Punt
1339 $errors = array( array( 'unknownerror-nocode' ) );
1342 // Cannot use dieUsageMsg() because extensions might return custom
1344 if ( $errors[0] instanceof Message
) {
1346 $code = $msg->getKey();
1348 $code = array_shift( $errors[0] );
1349 $msg = wfMessage( $code, $errors[0] );
1351 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1352 // Translate message to code, for backwards compatibility
1353 $code = ApiBase
::$messageMap[$code]['code'];
1356 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1360 * Throw a UsageException based on the errors in the Status object.
1363 * @param Status $status
1364 * @throws MWException
1366 public function dieStatus( $status ) {
1368 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1369 $this->dieUsage( $msg, $code );
1372 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1374 * Array that maps message keys to error messages. $1 and friends are replaced.
1376 public static $messageMap = array(
1377 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1378 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1379 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1381 // Messages from Title::getUserPermissionsErrors()
1382 'ns-specialprotected' => array(
1383 'code' => 'unsupportednamespace',
1384 'info' => "Pages in the Special namespace can't be edited"
1386 'protectedinterface' => array(
1387 'code' => 'protectednamespace-interface',
1388 'info' => "You're not allowed to edit interface messages"
1390 'namespaceprotected' => array(
1391 'code' => 'protectednamespace',
1392 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1394 'customcssprotected' => array(
1395 'code' => 'customcssprotected',
1396 'info' => "You're not allowed to edit custom CSS pages"
1398 'customjsprotected' => array(
1399 'code' => 'customjsprotected',
1400 'info' => "You're not allowed to edit custom JavaScript pages"
1402 'cascadeprotected' => array(
1403 'code' => 'cascadeprotected',
1404 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1406 'protectedpagetext' => array(
1407 'code' => 'protectedpage',
1408 'info' => "The \"\$1\" right is required to edit this page"
1410 'protect-cantedit' => array(
1411 'code' => 'cantedit',
1412 'info' => "You can't protect this page because you can't edit it"
1414 'delete-cantedit' => array(
1415 'code' => 'cantedit',
1416 'info' => "You can't delete this page because you can't edit it"
1418 'badaccess-group0' => array(
1419 'code' => 'permissiondenied',
1420 'info' => "Permission denied"
1421 ), // Generic permission denied message
1422 'badaccess-groups' => array(
1423 'code' => 'permissiondenied',
1424 'info' => "Permission denied"
1426 'titleprotected' => array(
1427 'code' => 'protectedtitle',
1428 'info' => "This title has been protected from creation"
1430 'nocreate-loggedin' => array(
1431 'code' => 'cantcreate',
1432 'info' => "You don't have permission to create new pages"
1434 'nocreatetext' => array(
1435 'code' => 'cantcreate-anon',
1436 'info' => "Anonymous users can't create new pages"
1438 'movenologintext' => array(
1439 'code' => 'cantmove-anon',
1440 'info' => "Anonymous users can't move pages"
1442 'movenotallowed' => array(
1443 'code' => 'cantmove',
1444 'info' => "You don't have permission to move pages"
1446 'confirmedittext' => array(
1447 'code' => 'confirmemail',
1448 'info' => "You must confirm your email address before you can edit"
1450 'blockedtext' => array(
1451 'code' => 'blocked',
1452 'info' => "You have been blocked from editing"
1454 'autoblockedtext' => array(
1455 'code' => 'autoblocked',
1456 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1459 // Miscellaneous interface messages
1460 'actionthrottledtext' => array(
1461 'code' => 'ratelimited',
1462 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1464 'alreadyrolled' => array(
1465 'code' => 'alreadyrolled',
1466 'info' => "The page you tried to rollback was already rolled back"
1468 'cantrollback' => array(
1469 'code' => 'onlyauthor',
1470 'info' => "The page you tried to rollback only has one author"
1472 'readonlytext' => array(
1473 'code' => 'readonly',
1474 'info' => "The wiki is currently in read-only mode"
1476 'sessionfailure' => array(
1477 'code' => 'badtoken',
1478 'info' => "Invalid token" ),
1479 'cannotdelete' => array(
1480 'code' => 'cantdelete',
1481 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1483 'notanarticle' => array(
1484 'code' => 'missingtitle',
1485 'info' => "The page you requested doesn't exist"
1487 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1489 'immobile_namespace' => array(
1490 'code' => 'immobilenamespace',
1491 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1493 'articleexists' => array(
1494 'code' => 'articleexists',
1495 'info' => "The destination article already exists and is not a redirect to the source article"
1497 'protectedpage' => array(
1498 'code' => 'protectedpage',
1499 'info' => "You don't have permission to perform this move"
1501 'hookaborted' => array(
1502 'code' => 'hookaborted',
1503 'info' => "The modification you tried to make was aborted by an extension hook"
1505 'cantmove-titleprotected' => array(
1506 'code' => 'protectedtitle',
1507 'info' => "The destination article has been protected from creation"
1509 'imagenocrossnamespace' => array(
1510 'code' => 'nonfilenamespace',
1511 'info' => "Can't move a file to a non-file namespace"
1513 'imagetypemismatch' => array(
1514 'code' => 'filetypemismatch',
1515 'info' => "The new file extension doesn't match its type"
1517 // 'badarticleerror' => shouldn't happen
1518 // 'badtitletext' => shouldn't happen
1519 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1520 'range_block_disabled' => array(
1521 'code' => 'rangedisabled',
1522 'info' => "Blocking IP ranges has been disabled"
1524 'nosuchusershort' => array(
1525 'code' => 'nosuchuser',
1526 'info' => "The user you specified doesn't exist"
1528 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1529 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1530 'ipb_already_blocked' => array(
1531 'code' => 'alreadyblocked',
1532 'info' => "The user you tried to block was already blocked"
1534 'ipb_blocked_as_range' => array(
1535 'code' => 'blockedasrange',
1536 '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."
1538 'ipb_cant_unblock' => array(
1539 'code' => 'cantunblock',
1540 'info' => "The block you specified was not found. It may have been unblocked already"
1542 'mailnologin' => array(
1543 'code' => 'cantsend',
1544 '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"
1546 'ipbblocked' => array(
1547 'code' => 'ipbblocked',
1548 'info' => 'You cannot block or unblock users while you are yourself blocked'
1550 'ipbnounblockself' => array(
1551 'code' => 'ipbnounblockself',
1552 'info' => 'You are not allowed to unblock yourself'
1554 'usermaildisabled' => array(
1555 'code' => 'usermaildisabled',
1556 'info' => "User email has been disabled"
1558 'blockedemailuser' => array(
1559 'code' => 'blockedfrommail',
1560 'info' => "You have been blocked from sending email"
1562 'notarget' => array(
1563 'code' => 'notarget',
1564 'info' => "You have not specified a valid target for this action"
1567 'code' => 'noemail',
1568 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1570 'rcpatroldisabled' => array(
1571 'code' => 'patroldisabled',
1572 'info' => "Patrolling is disabled on this wiki"
1574 'markedaspatrollederror-noautopatrol' => array(
1575 'code' => 'noautopatrol',
1576 'info' => "You don't have permission to patrol your own changes"
1578 'delete-toobig' => array(
1579 'code' => 'bigdelete',
1580 'info' => "You can't delete this page because it has more than \$1 revisions"
1582 'movenotallowedfile' => array(
1583 'code' => 'cantmovefile',
1584 'info' => "You don't have permission to move files"
1586 'userrights-no-interwiki' => array(
1587 'code' => 'nointerwikiuserrights',
1588 'info' => "You don't have permission to change user rights on other wikis"
1590 'userrights-nodatabase' => array(
1591 'code' => 'nosuchdatabase',
1592 'info' => "Database \"\$1\" does not exist or is not local"
1594 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1595 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1596 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1597 'import-rootpage-invalid' => array(
1598 'code' => 'import-rootpage-invalid',
1599 'info' => 'Root page is an invalid title'
1601 'import-rootpage-nosubpage' => array(
1602 'code' => 'import-rootpage-nosubpage',
1603 'info' => 'Namespace "$1" of the root page does not allow subpages'
1606 // API-specific messages
1607 'readrequired' => array(
1608 'code' => 'readapidenied',
1609 'info' => "You need read permission to use this module"
1611 'writedisabled' => array(
1612 'code' => 'noapiwrite',
1613 '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"
1615 'writerequired' => array(
1616 'code' => 'writeapidenied',
1617 'info' => "You're not allowed to edit this wiki through the API"
1619 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1620 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1621 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1622 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1623 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1624 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1625 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1626 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1627 'create-titleexists' => array(
1628 'code' => 'create-titleexists',
1629 'info' => "Existing titles can't be protected with 'create'"
1631 'missingtitle-createonly' => array(
1632 'code' => 'missingtitle-createonly',
1633 'info' => "Missing titles can only be protected with 'create'"
1635 'cantblock' => array( 'code' => 'cantblock',
1636 'info' => "You don't have permission to block users"
1638 'canthide' => array(
1639 'code' => 'canthide',
1640 'info' => "You don't have permission to hide user names from the block log"
1642 'cantblock-email' => array(
1643 'code' => 'cantblock-email',
1644 'info' => "You don't have permission to block users from sending email through the wiki"
1646 'unblock-notarget' => array(
1647 'code' => 'notarget',
1648 'info' => "Either the id or the user parameter must be set"
1650 'unblock-idanduser' => array(
1651 'code' => 'idanduser',
1652 'info' => "The id and user parameters can't be used together"
1654 'cantunblock' => array(
1655 'code' => 'permissiondenied',
1656 'info' => "You don't have permission to unblock users"
1658 'cannotundelete' => array(
1659 'code' => 'cantundelete',
1660 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1662 'permdenied-undelete' => array(
1663 'code' => 'permissiondenied',
1664 'info' => "You don't have permission to restore deleted revisions"
1666 'createonly-exists' => array(
1667 'code' => 'articleexists',
1668 'info' => "The article you tried to create has been created already"
1670 'nocreate-missing' => array(
1671 'code' => 'missingtitle',
1672 'info' => "The article you tried to edit doesn't exist"
1674 'nosuchrcid' => array(
1675 'code' => 'nosuchrcid',
1676 'info' => "There is no change with rcid \"\$1\""
1678 'protect-invalidaction' => array(
1679 'code' => 'protect-invalidaction',
1680 'info' => "Invalid protection type \"\$1\""
1682 'protect-invalidlevel' => array(
1683 'code' => 'protect-invalidlevel',
1684 'info' => "Invalid protection level \"\$1\""
1686 'toofewexpiries' => array(
1687 'code' => 'toofewexpiries',
1688 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1690 'cantimport' => array(
1691 'code' => 'cantimport',
1692 'info' => "You don't have permission to import pages"
1694 'cantimport-upload' => array(
1695 'code' => 'cantimport-upload',
1696 'info' => "You don't have permission to import uploaded pages"
1698 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1699 'importuploaderrorsize' => array(
1700 'code' => 'filetoobig',
1701 'info' => 'The file you uploaded is bigger than the maximum upload size'
1703 'importuploaderrorpartial' => array(
1704 'code' => 'partialupload',
1705 'info' => 'The file was only partially uploaded'
1707 'importuploaderrortemp' => array(
1708 'code' => 'notempdir',
1709 'info' => 'The temporary upload directory is missing'
1711 'importcantopen' => array(
1712 'code' => 'cantopenfile',
1713 'info' => "Couldn't open the uploaded file"
1715 'import-noarticle' => array(
1716 'code' => 'badinterwiki',
1717 'info' => 'Invalid interwiki title specified'
1719 'importbadinterwiki' => array(
1720 'code' => 'badinterwiki',
1721 'info' => 'Invalid interwiki title specified'
1723 'import-unknownerror' => array(
1724 'code' => 'import-unknownerror',
1725 'info' => "Unknown error on import: \"\$1\""
1727 'cantoverwrite-sharedfile' => array(
1728 'code' => 'cantoverwrite-sharedfile',
1729 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1731 'sharedfile-exists' => array(
1732 'code' => 'fileexists-sharedrepo-perm',
1733 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1735 'mustbeposted' => array(
1736 'code' => 'mustbeposted',
1737 'info' => "The \$1 module requires a POST request"
1741 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1743 'specialpage-cantexecute' => array(
1744 'code' => 'specialpage-cantexecute',
1745 'info' => "You don't have permission to view the results of this special page"
1747 'invalidoldimage' => array(
1748 'code' => 'invalidoldimage',
1749 'info' => 'The oldimage parameter has invalid format'
1751 'nodeleteablefile' => array(
1752 'code' => 'nodeleteablefile',
1753 'info' => 'No such old version of the file'
1755 'fileexists-forbidden' => array(
1756 'code' => 'fileexists-forbidden',
1757 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1759 'fileexists-shared-forbidden' => array(
1760 'code' => 'fileexists-shared-forbidden',
1761 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1763 'filerevert-badversion' => array(
1764 'code' => 'filerevert-badversion',
1765 'info' => 'There is no previous local version of this file with the provided timestamp.'
1768 // ApiEditPage messages
1769 'noimageredirect-anon' => array(
1770 'code' => 'noimageredirect-anon',
1771 'info' => "Anonymous users can't create image redirects"
1773 'noimageredirect-logged' => array(
1774 'code' => 'noimageredirect',
1775 'info' => "You don't have permission to create image redirects"
1777 'spamdetected' => array(
1778 'code' => 'spamdetected',
1779 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1781 'contenttoobig' => array(
1782 'code' => 'contenttoobig',
1783 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1785 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1786 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1787 'wasdeleted' => array(
1788 'code' => 'pagedeleted',
1789 'info' => "The page has been deleted since you fetched its timestamp"
1791 'blankpage' => array(
1792 'code' => 'emptypage',
1793 'info' => "Creating new, empty pages is not allowed"
1795 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1796 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1797 'missingtext' => array(
1799 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1801 'emptynewsection' => array(
1802 'code' => 'emptynewsection',
1803 'info' => 'Creating empty new sections is not possible.'
1805 'revwrongpage' => array(
1806 'code' => 'revwrongpage',
1807 'info' => "r\$1 is not a revision of \"\$2\""
1809 'undo-failure' => array(
1810 'code' => 'undofailure',
1811 'info' => 'Undo failed due to conflicting intermediate edits'
1814 // Messages from WikiPage::doEit()
1815 'edit-hook-aborted' => array(
1816 'code' => 'edit-hook-aborted',
1817 'info' => "Your edit was aborted by an ArticleSave hook"
1819 'edit-gone-missing' => array(
1820 'code' => 'edit-gone-missing',
1821 'info' => "The page you tried to edit doesn't seem to exist anymore"
1823 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1824 'edit-already-exists' => array(
1825 'code' => 'edit-already-exists',
1826 'info' => 'It seems the page you tried to create already exist'
1830 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1831 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1832 'uploaddisabled' => array(
1833 'code' => 'uploaddisabled',
1834 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1836 'copyuploaddisabled' => array(
1837 'code' => 'copyuploaddisabled',
1838 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1840 'copyuploadbaddomain' => array(
1841 'code' => 'copyuploadbaddomain',
1842 'info' => 'Uploads by URL are not allowed from this domain.'
1844 'copyuploadbadurl' => array(
1845 'code' => 'copyuploadbadurl',
1846 'info' => 'Upload not allowed from this URL.'
1849 'filename-tooshort' => array(
1850 'code' => 'filename-tooshort',
1851 'info' => 'The filename is too short'
1853 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1854 'illegal-filename' => array(
1855 'code' => 'illegal-filename',
1856 'info' => 'The filename is not allowed'
1858 'filetype-missing' => array(
1859 'code' => 'filetype-missing',
1860 'info' => 'The file is missing an extension'
1863 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1865 // @codingStandardsIgnoreEnd
1868 * Helper function for readonly errors
1870 public function dieReadOnly() {
1871 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1872 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1873 array( 'readonlyreason' => wfReadOnlyReason() ) );
1877 * Output the error message related to a certain array
1878 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1880 public function dieUsageMsg( $error ) {
1881 # most of the time we send a 1 element, so we might as well send it as
1882 # a string and make this an array here.
1883 if ( is_string( $error ) ) {
1884 $error = array( $error );
1886 $parsed = $this->parseMsg( $error );
1887 $this->dieUsage( $parsed['info'], $parsed['code'] );
1891 * Will only set a warning instead of failing if the global $wgDebugAPI
1892 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1893 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1896 public function dieUsageMsgOrDebug( $error ) {
1897 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1898 $this->dieUsageMsg( $error );
1901 if ( is_string( $error ) ) {
1902 $error = array( $error );
1904 $parsed = $this->parseMsg( $error );
1905 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1909 * Die with the $prefix.'badcontinue' error. This call is common enough to
1910 * make it into the base method.
1911 * @param bool $condition Will only die if this value is true
1914 protected function dieContinueUsageIf( $condition ) {
1917 'Invalid continue param. You should pass the original value returned by the previous query',
1923 * Return the error message related to a certain array
1924 * @param array $error Element of a getUserPermissionsErrors()-style array
1925 * @return array('code' => code, 'info' => info)
1927 public function parseMsg( $error ) {
1928 $error = (array)$error; // It seems strings sometimes make their way in here
1929 $key = array_shift( $error );
1931 // Check whether the error array was nested
1932 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1933 if ( is_array( $key ) ) {
1935 $key = array_shift( $error );
1938 if ( isset( self
::$messageMap[$key] ) ) {
1940 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1941 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1945 // If the key isn't present, throw an "unknown error"
1946 return $this->parseMsg( array( 'unknownerror', $key ) );
1950 * Internal code errors should be reported with this method
1951 * @param string $method Method or function name
1952 * @param string $message Error message
1953 * @throws MWException
1955 protected static function dieDebug( $method, $message ) {
1956 throw new MWException( "Internal error in $method: $message" );
1960 * Indicates if this module needs maxlag to be checked
1963 public function shouldCheckMaxlag() {
1968 * Indicates whether this module requires read rights
1971 public function isReadMode() {
1976 * Indicates whether this module requires write mode
1979 public function isWriteMode() {
1984 * Indicates whether this module must be called with a POST request
1987 public function mustBePosted() {
1992 * Returns whether this module requires a token to execute
1993 * It is used to show possible errors in action=paraminfo
1997 public function needsToken() {
2002 * Returns the token salt if there is one,
2003 * '' if the module doesn't require a salt,
2004 * else false if the module doesn't need a token
2005 * You have also to override needsToken()
2006 * Value is passed to User::getEditToken
2007 * @return bool|string|array
2009 public function getTokenSalt() {
2014 * Gets the user for whom to get the watchlist
2016 * @param array $params
2019 public function getWatchlistUser( $params ) {
2020 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2021 $user = User
::newFromName( $params['owner'], false );
2022 if ( !( $user && $user->getId() ) ) {
2023 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2025 $token = $user->getOption( 'watchlisttoken' );
2026 if ( $token == '' ||
$token != $params['token'] ) {
2028 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2033 if ( !$this->getUser()->isLoggedIn() ) {
2034 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2036 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2037 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2039 $user = $this->getUser();
2046 * @return bool|string|array Returns a false if the module has no help URL,
2047 * else returns a (array of) string
2049 public function getHelpUrls() {
2054 * This formerly attempted to return a list of all possible errors returned
2055 * by the module. However, this was impossible to maintain in many cases
2056 * since errors could come from other areas of MediaWiki and in some cases
2057 * from arbitrary extension hooks. Since a partial list claiming to be
2058 * comprehensive is unlikely to be useful, it was removed.
2060 * @deprecated since 1.24
2063 public function getPossibleErrors() {
2064 wfDeprecated( __METHOD__
, '1.24' );
2069 * @see self::getPossibleErrors()
2070 * @deprecated since 1.24
2073 public function getFinalPossibleErrors() {
2074 wfDeprecated( __METHOD__
, '1.24' );
2079 * @see self::getPossibleErrors()
2080 * @deprecated since 1.24
2083 public function parseErrors( $errors ) {
2084 wfDeprecated( __METHOD__
, '1.24' );
2089 * Profiling: total module execution time
2091 private $mTimeIn = 0, $mModuleTime = 0;
2094 * Start module profiling
2096 public function profileIn() {
2097 if ( $this->mTimeIn
!== 0 ) {
2098 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2100 $this->mTimeIn
= microtime( true );
2101 wfProfileIn( $this->getModuleProfileName() );
2105 * End module profiling
2107 public function profileOut() {
2108 if ( $this->mTimeIn
=== 0 ) {
2109 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2111 if ( $this->mDBTimeIn
!== 0 ) {
2114 'Must be called after database profiling is done with profileDBOut()'
2118 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2120 wfProfileOut( $this->getModuleProfileName() );
2124 * When modules crash, sometimes it is needed to do a profileOut() regardless
2125 * of the profiling state the module was in. This method does such cleanup.
2127 public function safeProfileOut() {
2128 if ( $this->mTimeIn
!== 0 ) {
2129 if ( $this->mDBTimeIn
!== 0 ) {
2130 $this->profileDBOut();
2132 $this->profileOut();
2137 * Total time the module was executed
2140 public function getProfileTime() {
2141 if ( $this->mTimeIn
!== 0 ) {
2142 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2145 return $this->mModuleTime
;
2149 * Profiling: database execution time
2151 private $mDBTimeIn = 0, $mDBTime = 0;
2154 * Start module profiling
2156 public function profileDBIn() {
2157 if ( $this->mTimeIn
=== 0 ) {
2160 'Must be called while profiling the entire module with profileIn()'
2163 if ( $this->mDBTimeIn
!== 0 ) {
2164 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2166 $this->mDBTimeIn
= microtime( true );
2167 wfProfileIn( $this->getModuleProfileName( true ) );
2171 * End database profiling
2173 public function profileDBOut() {
2174 if ( $this->mTimeIn
=== 0 ) {
2175 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2176 'the entire module with profileIn()' );
2178 if ( $this->mDBTimeIn
=== 0 ) {
2179 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2182 $time = microtime( true ) - $this->mDBTimeIn
;
2183 $this->mDBTimeIn
= 0;
2185 $this->mDBTime +
= $time;
2186 $this->getMain()->mDBTime +
= $time;
2187 wfProfileOut( $this->getModuleProfileName( true ) );
2191 * Total time the module used the database
2194 public function getProfileDBTime() {
2195 if ( $this->mDBTimeIn
!== 0 ) {
2196 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2199 return $this->mDBTime
;
2203 * Gets a default slave database connection object
2204 * @return DatabaseBase
2206 protected function getDB() {
2207 if ( !isset( $this->mSlaveDB
) ) {
2208 $this->profileDBIn();
2209 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2210 $this->profileDBOut();
2213 return $this->mSlaveDB
;
2217 * Debugging function that prints a value and an optional backtrace
2218 * @param mixed $value Value to print
2219 * @param string $name Description of the printed value
2220 * @param bool $backtrace If true, print a backtrace
2222 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2223 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2224 var_export( $value );
2226 print "\n" . wfBacktrace();