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 ( $type === 'submodule' ) {
439 $type = $this->getModuleManager()->getNames( $paramName );
442 if ( is_array( $type ) ) {
445 foreach ( $type as $t ) {
447 $nothingPrompt = 'Can be empty, or ';
452 $desc .= $paramPrefix . $nothingPrompt . $prompt;
453 $choicesstring = implode( ', ', $choices );
454 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
455 $hintPipeSeparated = false;
459 // Special handling because namespaces are
460 // type-limited, yet they are not given
461 $desc .= $paramPrefix . $prompt;
462 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
463 100, $descWordwrap );
464 $hintPipeSeparated = false;
467 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
468 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
469 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
474 $s = $multi ?
's' : '';
475 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
476 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
477 if ( $hasMin ||
$hasMax ) {
479 $intRangeStr = "The value$s must be no less than " .
480 "{$paramSettings[self::PARAM_MIN]}";
481 } elseif ( !$hasMin ) {
482 $intRangeStr = "The value$s must be no more than " .
483 "{$paramSettings[self::PARAM_MAX]}";
485 $intRangeStr = "The value$s must be between " .
486 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
489 $desc .= $paramPrefix . $intRangeStr;
493 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
499 if ( $hintPipeSeparated ) {
500 $desc .= $paramPrefix . "Separate values with '|'";
503 $isArray = is_array( $type );
505 ||
$isArray && count( $type ) > self
::LIMIT_SML1
507 $desc .= $paramPrefix . "Maximum number of values " .
508 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
513 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
514 if ( !is_null( $default ) && $default !== false ) {
515 $desc .= $paramPrefix . "Default: $default";
518 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
528 * Returns the description string for this module
529 * @return string|array
531 protected function getDescription() {
536 * Returns usage examples for this module. Return false if no examples are available.
537 * @return bool|string|array
539 protected function getExamples() {
544 * Returns an array of allowed parameters (parameter name) => (default
545 * value) or (parameter name) => (array with PARAM_* constants as keys)
546 * Don't call this function directly: use getFinalParams() to allow
547 * hooks to modify parameters as needed.
549 * Some derived classes may choose to handle an integer $flags parameter
550 * in the overriding methods. Callers of this method can pass zero or
551 * more OR-ed flags like GET_VALUES_FOR_HELP.
555 protected function getAllowedParams( /* $flags = 0 */ ) {
556 // int $flags is not declared because it causes "Strict standards"
557 // warning. Most derived classes do not implement it.
562 * Returns an array of parameter descriptions.
563 * Don't call this function directly: use getFinalParamDescription() to
564 * allow hooks to modify descriptions as needed.
565 * @return array|bool False on no parameter descriptions
567 protected function getParamDescription() {
572 * Get final list of parameters, after hooks have had a chance to
573 * tweak it as needed.
575 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
576 * @return array|bool False on no parameters
577 * @since 1.21 $flags param added
579 public function getFinalParams( $flags = 0 ) {
580 $params = $this->getAllowedParams( $flags );
581 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
587 * Get final parameter descriptions, after hooks have had a chance to tweak it as
590 * @return array|bool False on no parameter descriptions
592 public function getFinalParamDescription() {
593 $desc = $this->getParamDescription();
594 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
600 * Formerly used to fetch a list of possible properites in the result,
601 * somehow organized with respect to the prop parameter that causes them to
602 * be returned. The specific semantics of the return value was never
603 * specified. Since this was never possible to be accurately updated, it
606 * @deprecated since 1.24
609 protected function getResultProperties() {
610 wfDeprecated( __METHOD__
, '1.24' );
615 * @see self::getResultProperties()
616 * @deprecated since 1.24
619 public function getFinalResultProperties() {
620 wfDeprecated( __METHOD__
, '1.24' );
625 * @see self::getResultProperties()
626 * @deprecated since 1.24
628 protected static function addTokenProperties( &$props, $tokenFunctions ) {
629 wfDeprecated( __METHOD__
, '1.24' );
633 * Get final module description, after hooks have had a chance to tweak it as
636 * @return array|bool False on no parameters
638 public function getFinalDescription() {
639 $desc = $this->getDescription();
640 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
646 * This method mangles parameter name based on the prefix supplied to the constructor.
647 * Override this method to change parameter name during runtime
648 * @param string $paramName Parameter name
649 * @return string Prefixed parameter name
651 public function encodeParamName( $paramName ) {
652 return $this->mModulePrefix
. $paramName;
656 * Using getAllowedParams(), this function makes an array of the values
657 * provided by the user, with key being the name of the variable, and
658 * value - validated value from user or default. limits will not be
659 * parsed if $parseLimit is set to false; use this when the max
660 * limit is not definitive yet, e.g. when getting revisions.
661 * @param bool $parseLimit True by default
664 public function extractRequestParams( $parseLimit = true ) {
665 // Cache parameters, for performance and to avoid bug 24564.
666 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
667 $params = $this->getFinalParams();
670 if ( $params ) { // getFinalParams() can return false
671 foreach ( $params as $paramName => $paramSettings ) {
672 $results[$paramName] = $this->getParameterFromSettings(
673 $paramName, $paramSettings, $parseLimit );
676 $this->mParamCache
[$parseLimit] = $results;
679 return $this->mParamCache
[$parseLimit];
683 * Get a value for the given parameter
684 * @param string $paramName Parameter name
685 * @param bool $parseLimit See extractRequestParams()
686 * @return mixed Parameter value
688 protected function getParameter( $paramName, $parseLimit = true ) {
689 $params = $this->getFinalParams();
690 $paramSettings = $params[$paramName];
692 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
696 * Die if none or more than one of a certain set of parameters is set and not false.
698 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
699 * @param string $required,... Names of parameters of which exactly one must be set
701 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
702 $required = func_get_args();
703 array_shift( $required );
704 $p = $this->getModulePrefix();
706 $intersection = array_intersect( array_keys( array_filter( $params,
707 array( $this, "parameterNotEmpty" ) ) ), $required );
709 if ( count( $intersection ) > 1 ) {
711 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
713 } elseif ( count( $intersection ) == 0 ) {
715 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
722 * @see self::getPossibleErrors()
723 * @deprecated since 1.24
726 public function getRequireOnlyOneParameterErrorMessages( $params ) {
727 wfDeprecated( __METHOD__
, '1.24' );
732 * Die if more than one of a certain set of parameters is set and not false.
734 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
735 * @param string $required,... Names of parameters of which at most one must be set
737 public function requireMaxOneParameter( $params, $required /*...*/ ) {
738 $required = func_get_args();
739 array_shift( $required );
740 $p = $this->getModulePrefix();
742 $intersection = array_intersect( array_keys( array_filter( $params,
743 array( $this, "parameterNotEmpty" ) ) ), $required );
745 if ( count( $intersection ) > 1 ) {
747 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
754 * @see self::getPossibleErrors()
755 * @deprecated since 1.24
758 public function getRequireMaxOneParameterErrorMessages( $params ) {
759 wfDeprecated( __METHOD__
, '1.24' );
764 * Die if none of a certain set of parameters is set and not false.
767 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
768 * @param string $required,... Names of parameters of which at least one must be set
770 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
771 $required = func_get_args();
772 array_shift( $required );
773 $p = $this->getModulePrefix();
775 $intersection = array_intersect(
776 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
780 if ( count( $intersection ) == 0 ) {
781 $this->dieUsage( "At least one of the parameters {$p}" .
782 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
787 * @see self::getPossibleErrors()
788 * @deprecated since 1.24
791 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
792 wfDeprecated( __METHOD__
, '1.24' );
797 * Get a WikiPage object from a title or pageid param, if possible.
798 * Can die, if no param is set or if the title or page id is not valid.
800 * @param array $params
801 * @param bool|string $load Whether load the object's state from the database:
802 * - false: don't load (if the pageid is given, it will still be loaded)
803 * - 'fromdb': load from a slave database
804 * - 'fromdbmaster': load from the master database
807 public function getTitleOrPageId( $params, $load = false ) {
808 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
811 if ( isset( $params['title'] ) ) {
812 $titleObj = Title
::newFromText( $params['title'] );
813 if ( !$titleObj ||
$titleObj->isExternal() ) {
814 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
816 if ( !$titleObj->canExist() ) {
817 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
819 $pageObj = WikiPage
::factory( $titleObj );
820 if ( $load !== false ) {
821 $pageObj->loadPageData( $load );
823 } elseif ( isset( $params['pageid'] ) ) {
824 if ( $load === false ) {
827 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
829 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
837 * @see self::getPossibleErrors()
838 * @deprecated since 1.24
841 public function getTitleOrPageIdErrorMessage() {
842 wfDeprecated( __METHOD__
, '1.24' );
847 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
849 * @param object $x Parameter to check is not null/false
852 private function parameterNotEmpty( $x ) {
853 return !is_null( $x ) && $x !== false;
857 * Return true if we're to watch the page, false if not, null if no change.
858 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
859 * @param Title $titleObj The page under consideration
860 * @param string $userOption The user option to consider when $watchlist=preferences.
861 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
864 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
866 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
868 switch ( $watchlist ) {
876 # If the user is already watching, don't bother checking
877 if ( $userWatching ) {
880 # If no user option was passed, use watchdefault and watchcreations
881 if ( is_null( $userOption ) ) {
882 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
883 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
886 # Watch the article based on the user preference
887 return $this->getUser()->getBoolOption( $userOption );
890 return $userWatching;
893 return $userWatching;
898 * Set a watch (or unwatch) based the based on a watchlist parameter.
899 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
900 * @param Title $titleObj The article's title to change
901 * @param string $userOption The user option to consider when $watch=preferences
903 protected function setWatch( $watch, $titleObj, $userOption = null ) {
904 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
905 if ( $value === null ) {
909 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
913 * Using the settings determine the value for the given parameter
915 * @param string $paramName Parameter name
916 * @param array|mixed $paramSettings Default value or an array of settings
917 * using PARAM_* constants.
918 * @param bool $parseLimit Parse limit?
919 * @return mixed Parameter value
921 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
922 // Some classes may decide to change parameter names
923 $encParamName = $this->encodeParamName( $paramName );
925 if ( !is_array( $paramSettings ) ) {
926 $default = $paramSettings;
928 $type = gettype( $paramSettings );
933 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
934 ?
$paramSettings[self
::PARAM_DFLT
]
936 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
937 ?
$paramSettings[self
::PARAM_ISMULTI
]
939 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
940 ?
$paramSettings[self
::PARAM_TYPE
]
942 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
943 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
945 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
946 ?
$paramSettings[self
::PARAM_DEPRECATED
]
948 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
949 ?
$paramSettings[self
::PARAM_REQUIRED
]
952 // When type is not given, and no choices, the type is the same as $default
953 if ( !isset( $type ) ) {
954 if ( isset( $default ) ) {
955 $type = gettype( $default );
957 $type = 'NULL'; // allow everything
962 if ( $type == 'boolean' ) {
963 if ( isset( $default ) && $default !== false ) {
964 // Having a default value of anything other than 'false' is not allowed
967 "Boolean param $encParamName's default is set to '$default'. " .
968 "Boolean parameters must default to false."
972 $value = $this->getMain()->getCheck( $encParamName );
973 } elseif ( $type == 'upload' ) {
974 if ( isset( $default ) ) {
975 // Having a default value is not allowed
978 "File upload param $encParamName's default is set to " .
979 "'$default'. File upload parameters may not have a default." );
982 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
984 $value = $this->getMain()->getUpload( $encParamName );
985 if ( !$value->exists() ) {
986 // This will get the value without trying to normalize it
987 // (because trying to normalize a large binary file
988 // accidentally uploaded as a field fails spectacularly)
989 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
990 if ( $value !== null ) {
992 "File upload param $encParamName is not a file upload; " .
993 "be sure to use multipart/form-data for your POST and include " .
994 "a filename in the Content-Disposition header.",
995 "badupload_{$encParamName}"
1000 $value = $this->getMain()->getVal( $encParamName, $default );
1002 if ( isset( $value ) && $type == 'namespace' ) {
1003 $type = MWNamespace
::getValidNamespaces();
1005 if ( isset( $value ) && $type == 'submodule' ) {
1006 $type = $this->getModuleManager()->getNames( $paramName );
1010 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1011 $value = $this->parseMultiValue(
1015 is_array( $type ) ?
$type : null
1019 // More validation only when choices were not given
1020 // choices were validated in parseMultiValue()
1021 if ( isset( $value ) ) {
1022 if ( !is_array( $type ) ) {
1024 case 'NULL': // nothing to do
1027 if ( $required && $value === '' ) {
1028 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1031 case 'integer': // Force everything using intval() and optionally validate limits
1032 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1033 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1034 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1035 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1037 if ( is_array( $value ) ) {
1038 $value = array_map( 'intval', $value );
1039 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1040 foreach ( $value as &$v ) {
1041 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1045 $value = intval( $value );
1046 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1047 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1052 if ( !$parseLimit ) {
1053 // Don't do any validation whatsoever
1056 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1057 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1061 "MAX1 or MAX2 are not defined for the limit $encParamName"
1065 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1067 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1068 if ( $value == 'max' ) {
1069 $value = $this->getMain()->canApiHighLimits()
1070 ?
$paramSettings[self
::PARAM_MAX2
]
1071 : $paramSettings[self
::PARAM_MAX
];
1072 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1074 $value = intval( $value );
1075 $this->validateLimit(
1079 $paramSettings[self
::PARAM_MAX
],
1080 $paramSettings[self
::PARAM_MAX2
]
1086 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1090 if ( is_array( $value ) ) {
1091 foreach ( $value as $key => $val ) {
1092 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1095 $value = $this->validateTimestamp( $value, $encParamName );
1099 if ( is_array( $value ) ) {
1100 foreach ( $value as $key => $val ) {
1101 $value[$key] = $this->validateUser( $val, $encParamName );
1104 $value = $this->validateUser( $value, $encParamName );
1107 case 'upload': // nothing to do
1110 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1114 // Throw out duplicates if requested
1115 if ( !$dupes && is_array( $value ) ) {
1116 $value = array_unique( $value );
1119 // Set a warning if a deprecated parameter has been passed
1120 if ( $deprecated && $value !== false ) {
1121 $this->setWarning( "The $encParamName parameter has been deprecated." );
1123 } elseif ( $required ) {
1124 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1131 * Return an array of values that were given in a 'a|b|c' notation,
1132 * after it optionally validates them against the list allowed values.
1134 * @param string $valueName The name of the parameter (for error
1136 * @param mixed $value The value being parsed
1137 * @param bool $allowMultiple Can $value contain more than one value
1139 * @param string[]|null $allowedValues An array of values to check against. If
1140 * null, all values are accepted.
1141 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1143 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1144 if ( trim( $value ) === '' && $allowMultiple ) {
1148 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1149 // because it unstubs $wgUser
1150 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1151 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1155 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1156 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1157 "the limit is $sizeLimit" );
1160 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1161 // Bug 33482 - Allow entries with | in them for non-multiple values
1162 if ( in_array( $value, $allowedValues, true ) ) {
1166 $possibleValues = is_array( $allowedValues )
1167 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1170 "Only one $possibleValues is allowed for parameter '$valueName'",
1171 "multival_$valueName"
1175 if ( is_array( $allowedValues ) ) {
1176 // Check for unknown values
1177 $unknown = array_diff( $valuesList, $allowedValues );
1178 if ( count( $unknown ) ) {
1179 if ( $allowMultiple ) {
1180 $s = count( $unknown ) > 1 ?
's' : '';
1181 $vals = implode( ", ", $unknown );
1182 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1185 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1186 "unknown_$valueName"
1190 // Now throw them out
1191 $valuesList = array_intersect( $valuesList, $allowedValues );
1194 return $allowMultiple ?
$valuesList : $valuesList[0];
1198 * Validate the value against the minimum and user/bot maximum limits.
1199 * Prints usage info on failure.
1200 * @param string $paramName Parameter name
1201 * @param int $value Parameter value
1202 * @param int|null $min Minimum value
1203 * @param int|null $max Maximum value for users
1204 * @param int $botMax Maximum value for sysops/bots
1205 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1207 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1208 if ( !is_null( $min ) && $value < $min ) {
1210 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1211 $this->warnOrDie( $msg, $enforceLimits );
1215 // Minimum is always validated, whereas maximum is checked only if not
1216 // running in internal call mode
1217 if ( $this->getMain()->isInternalMode() ) {
1221 // Optimization: do not check user's bot status unless really needed -- skips db query
1222 // assumes $botMax >= $max
1223 if ( !is_null( $max ) && $value > $max ) {
1224 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1225 if ( $value > $botMax ) {
1226 $msg = $this->encodeParamName( $paramName ) .
1227 " may not be over $botMax (set to $value) for bots or sysops";
1228 $this->warnOrDie( $msg, $enforceLimits );
1232 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1233 $this->warnOrDie( $msg, $enforceLimits );
1240 * Validate and normalize of parameters of type 'timestamp'
1241 * @param string $value Parameter value
1242 * @param string $encParamName Parameter name
1243 * @return string Validated and normalized parameter
1245 function validateTimestamp( $value, $encParamName ) {
1246 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1247 if ( $unixTimestamp === false ) {
1249 "Invalid value '$value' for timestamp parameter $encParamName",
1250 "badtimestamp_{$encParamName}"
1254 return wfTimestamp( TS_MW
, $unixTimestamp );
1258 * Validate and normalize of parameters of type 'user'
1259 * @param string $value Parameter value
1260 * @param string $encParamName Parameter name
1261 * @return string Validated and normalized parameter
1263 private function validateUser( $value, $encParamName ) {
1264 $title = Title
::makeTitleSafe( NS_USER
, $value );
1265 if ( $title === null ) {
1267 "Invalid value '$value' for user parameter $encParamName",
1268 "baduser_{$encParamName}"
1272 return $title->getText();
1276 * Adds a warning to the output, else dies
1278 * @param string $msg Message to show as a warning, or error message if dying
1279 * @param bool $enforceLimits Whether this is an enforce (die)
1281 private function warnOrDie( $msg, $enforceLimits = false ) {
1282 if ( $enforceLimits ) {
1283 $this->dieUsage( $msg, 'integeroutofrange' );
1286 $this->setWarning( $msg );
1290 * Truncate an array to a certain length.
1291 * @param array $arr Array to truncate
1292 * @param int $limit Maximum length
1293 * @return bool True if the array was truncated, false otherwise
1295 public static function truncateArray( &$arr, $limit ) {
1297 while ( count( $arr ) > $limit ) {
1306 * Throw a UsageException, which will (if uncaught) call the main module's
1307 * error handler and die with an error message.
1309 * @param string $description One-line human-readable description of the
1310 * error condition, e.g., "The API requires a valid action parameter"
1311 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1312 * automated identification of the error, e.g., 'unknown_action'
1313 * @param int $httpRespCode HTTP response code
1314 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1315 * @throws UsageException
1317 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1318 Profiler
::instance()->close();
1319 throw new UsageException(
1321 $this->encodeParamName( $errorCode ),
1328 * Get error (as code, string) from a Status object.
1331 * @param Status $status
1332 * @return array Array of code and error string
1334 public function getErrorFromStatus( $status ) {
1335 if ( $status->isGood() ) {
1336 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1339 $errors = $status->getErrorsArray();
1341 // No errors? Assume the warnings should be treated as errors
1342 $errors = $status->getWarningsArray();
1345 // Still no errors? Punt
1346 $errors = array( array( 'unknownerror-nocode' ) );
1349 // Cannot use dieUsageMsg() because extensions might return custom
1351 if ( $errors[0] instanceof Message
) {
1353 $code = $msg->getKey();
1355 $code = array_shift( $errors[0] );
1356 $msg = wfMessage( $code, $errors[0] );
1358 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1359 // Translate message to code, for backwards compatibility
1360 $code = ApiBase
::$messageMap[$code]['code'];
1363 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1367 * Throw a UsageException based on the errors in the Status object.
1370 * @param Status $status
1371 * @throws MWException
1373 public function dieStatus( $status ) {
1375 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1376 $this->dieUsage( $msg, $code );
1379 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1381 * Array that maps message keys to error messages. $1 and friends are replaced.
1383 public static $messageMap = array(
1384 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1385 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1386 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1388 // Messages from Title::getUserPermissionsErrors()
1389 'ns-specialprotected' => array(
1390 'code' => 'unsupportednamespace',
1391 'info' => "Pages in the Special namespace can't be edited"
1393 'protectedinterface' => array(
1394 'code' => 'protectednamespace-interface',
1395 'info' => "You're not allowed to edit interface messages"
1397 'namespaceprotected' => array(
1398 'code' => 'protectednamespace',
1399 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1401 'customcssprotected' => array(
1402 'code' => 'customcssprotected',
1403 'info' => "You're not allowed to edit custom CSS pages"
1405 'customjsprotected' => array(
1406 'code' => 'customjsprotected',
1407 'info' => "You're not allowed to edit custom JavaScript pages"
1409 'cascadeprotected' => array(
1410 'code' => 'cascadeprotected',
1411 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1413 'protectedpagetext' => array(
1414 'code' => 'protectedpage',
1415 'info' => "The \"\$1\" right is required to edit this page"
1417 'protect-cantedit' => array(
1418 'code' => 'cantedit',
1419 'info' => "You can't protect this page because you can't edit it"
1421 'delete-cantedit' => array(
1422 'code' => 'cantedit',
1423 'info' => "You can't delete this page because you can't edit it"
1425 'badaccess-group0' => array(
1426 'code' => 'permissiondenied',
1427 'info' => "Permission denied"
1428 ), // Generic permission denied message
1429 'badaccess-groups' => array(
1430 'code' => 'permissiondenied',
1431 'info' => "Permission denied"
1433 'titleprotected' => array(
1434 'code' => 'protectedtitle',
1435 'info' => "This title has been protected from creation"
1437 'nocreate-loggedin' => array(
1438 'code' => 'cantcreate',
1439 'info' => "You don't have permission to create new pages"
1441 'nocreatetext' => array(
1442 'code' => 'cantcreate-anon',
1443 'info' => "Anonymous users can't create new pages"
1445 'movenologintext' => array(
1446 'code' => 'cantmove-anon',
1447 'info' => "Anonymous users can't move pages"
1449 'movenotallowed' => array(
1450 'code' => 'cantmove',
1451 'info' => "You don't have permission to move pages"
1453 'confirmedittext' => array(
1454 'code' => 'confirmemail',
1455 'info' => "You must confirm your email address before you can edit"
1457 'blockedtext' => array(
1458 'code' => 'blocked',
1459 'info' => "You have been blocked from editing"
1461 'autoblockedtext' => array(
1462 'code' => 'autoblocked',
1463 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1466 // Miscellaneous interface messages
1467 'actionthrottledtext' => array(
1468 'code' => 'ratelimited',
1469 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1471 'alreadyrolled' => array(
1472 'code' => 'alreadyrolled',
1473 'info' => "The page you tried to rollback was already rolled back"
1475 'cantrollback' => array(
1476 'code' => 'onlyauthor',
1477 'info' => "The page you tried to rollback only has one author"
1479 'readonlytext' => array(
1480 'code' => 'readonly',
1481 'info' => "The wiki is currently in read-only mode"
1483 'sessionfailure' => array(
1484 'code' => 'badtoken',
1485 'info' => "Invalid token" ),
1486 'cannotdelete' => array(
1487 'code' => 'cantdelete',
1488 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1490 'notanarticle' => array(
1491 'code' => 'missingtitle',
1492 'info' => "The page you requested doesn't exist"
1494 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1496 'immobile_namespace' => array(
1497 'code' => 'immobilenamespace',
1498 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1500 'articleexists' => array(
1501 'code' => 'articleexists',
1502 'info' => "The destination article already exists and is not a redirect to the source article"
1504 'protectedpage' => array(
1505 'code' => 'protectedpage',
1506 'info' => "You don't have permission to perform this move"
1508 'hookaborted' => array(
1509 'code' => 'hookaborted',
1510 'info' => "The modification you tried to make was aborted by an extension hook"
1512 'cantmove-titleprotected' => array(
1513 'code' => 'protectedtitle',
1514 'info' => "The destination article has been protected from creation"
1516 'imagenocrossnamespace' => array(
1517 'code' => 'nonfilenamespace',
1518 'info' => "Can't move a file to a non-file namespace"
1520 'imagetypemismatch' => array(
1521 'code' => 'filetypemismatch',
1522 'info' => "The new file extension doesn't match its type"
1524 // 'badarticleerror' => shouldn't happen
1525 // 'badtitletext' => shouldn't happen
1526 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1527 'range_block_disabled' => array(
1528 'code' => 'rangedisabled',
1529 'info' => "Blocking IP ranges has been disabled"
1531 'nosuchusershort' => array(
1532 'code' => 'nosuchuser',
1533 'info' => "The user you specified doesn't exist"
1535 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1536 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1537 'ipb_already_blocked' => array(
1538 'code' => 'alreadyblocked',
1539 'info' => "The user you tried to block was already blocked"
1541 'ipb_blocked_as_range' => array(
1542 'code' => 'blockedasrange',
1543 '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."
1545 'ipb_cant_unblock' => array(
1546 'code' => 'cantunblock',
1547 'info' => "The block you specified was not found. It may have been unblocked already"
1549 'mailnologin' => array(
1550 'code' => 'cantsend',
1551 '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"
1553 'ipbblocked' => array(
1554 'code' => 'ipbblocked',
1555 'info' => 'You cannot block or unblock users while you are yourself blocked'
1557 'ipbnounblockself' => array(
1558 'code' => 'ipbnounblockself',
1559 'info' => 'You are not allowed to unblock yourself'
1561 'usermaildisabled' => array(
1562 'code' => 'usermaildisabled',
1563 'info' => "User email has been disabled"
1565 'blockedemailuser' => array(
1566 'code' => 'blockedfrommail',
1567 'info' => "You have been blocked from sending email"
1569 'notarget' => array(
1570 'code' => 'notarget',
1571 'info' => "You have not specified a valid target for this action"
1574 'code' => 'noemail',
1575 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1577 'rcpatroldisabled' => array(
1578 'code' => 'patroldisabled',
1579 'info' => "Patrolling is disabled on this wiki"
1581 'markedaspatrollederror-noautopatrol' => array(
1582 'code' => 'noautopatrol',
1583 'info' => "You don't have permission to patrol your own changes"
1585 'delete-toobig' => array(
1586 'code' => 'bigdelete',
1587 'info' => "You can't delete this page because it has more than \$1 revisions"
1589 'movenotallowedfile' => array(
1590 'code' => 'cantmovefile',
1591 'info' => "You don't have permission to move files"
1593 'userrights-no-interwiki' => array(
1594 'code' => 'nointerwikiuserrights',
1595 'info' => "You don't have permission to change user rights on other wikis"
1597 'userrights-nodatabase' => array(
1598 'code' => 'nosuchdatabase',
1599 'info' => "Database \"\$1\" does not exist or is not local"
1601 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1602 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1603 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1604 'import-rootpage-invalid' => array(
1605 'code' => 'import-rootpage-invalid',
1606 'info' => 'Root page is an invalid title'
1608 'import-rootpage-nosubpage' => array(
1609 'code' => 'import-rootpage-nosubpage',
1610 'info' => 'Namespace "$1" of the root page does not allow subpages'
1613 // API-specific messages
1614 'readrequired' => array(
1615 'code' => 'readapidenied',
1616 'info' => "You need read permission to use this module"
1618 'writedisabled' => array(
1619 'code' => 'noapiwrite',
1620 '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"
1622 'writerequired' => array(
1623 'code' => 'writeapidenied',
1624 'info' => "You're not allowed to edit this wiki through the API"
1626 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1627 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1628 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1629 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1630 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1631 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1632 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1633 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1634 'create-titleexists' => array(
1635 'code' => 'create-titleexists',
1636 'info' => "Existing titles can't be protected with 'create'"
1638 'missingtitle-createonly' => array(
1639 'code' => 'missingtitle-createonly',
1640 'info' => "Missing titles can only be protected with 'create'"
1642 'cantblock' => array( 'code' => 'cantblock',
1643 'info' => "You don't have permission to block users"
1645 'canthide' => array(
1646 'code' => 'canthide',
1647 'info' => "You don't have permission to hide user names from the block log"
1649 'cantblock-email' => array(
1650 'code' => 'cantblock-email',
1651 'info' => "You don't have permission to block users from sending email through the wiki"
1653 'unblock-notarget' => array(
1654 'code' => 'notarget',
1655 'info' => "Either the id or the user parameter must be set"
1657 'unblock-idanduser' => array(
1658 'code' => 'idanduser',
1659 'info' => "The id and user parameters can't be used together"
1661 'cantunblock' => array(
1662 'code' => 'permissiondenied',
1663 'info' => "You don't have permission to unblock users"
1665 'cannotundelete' => array(
1666 'code' => 'cantundelete',
1667 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1669 'permdenied-undelete' => array(
1670 'code' => 'permissiondenied',
1671 'info' => "You don't have permission to restore deleted revisions"
1673 'createonly-exists' => array(
1674 'code' => 'articleexists',
1675 'info' => "The article you tried to create has been created already"
1677 'nocreate-missing' => array(
1678 'code' => 'missingtitle',
1679 'info' => "The article you tried to edit doesn't exist"
1681 'nosuchrcid' => array(
1682 'code' => 'nosuchrcid',
1683 'info' => "There is no change with rcid \"\$1\""
1685 'protect-invalidaction' => array(
1686 'code' => 'protect-invalidaction',
1687 'info' => "Invalid protection type \"\$1\""
1689 'protect-invalidlevel' => array(
1690 'code' => 'protect-invalidlevel',
1691 'info' => "Invalid protection level \"\$1\""
1693 'toofewexpiries' => array(
1694 'code' => 'toofewexpiries',
1695 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1697 'cantimport' => array(
1698 'code' => 'cantimport',
1699 'info' => "You don't have permission to import pages"
1701 'cantimport-upload' => array(
1702 'code' => 'cantimport-upload',
1703 'info' => "You don't have permission to import uploaded pages"
1705 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1706 'importuploaderrorsize' => array(
1707 'code' => 'filetoobig',
1708 'info' => 'The file you uploaded is bigger than the maximum upload size'
1710 'importuploaderrorpartial' => array(
1711 'code' => 'partialupload',
1712 'info' => 'The file was only partially uploaded'
1714 'importuploaderrortemp' => array(
1715 'code' => 'notempdir',
1716 'info' => 'The temporary upload directory is missing'
1718 'importcantopen' => array(
1719 'code' => 'cantopenfile',
1720 'info' => "Couldn't open the uploaded file"
1722 'import-noarticle' => array(
1723 'code' => 'badinterwiki',
1724 'info' => 'Invalid interwiki title specified'
1726 'importbadinterwiki' => array(
1727 'code' => 'badinterwiki',
1728 'info' => 'Invalid interwiki title specified'
1730 'import-unknownerror' => array(
1731 'code' => 'import-unknownerror',
1732 'info' => "Unknown error on import: \"\$1\""
1734 'cantoverwrite-sharedfile' => array(
1735 'code' => 'cantoverwrite-sharedfile',
1736 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1738 'sharedfile-exists' => array(
1739 'code' => 'fileexists-sharedrepo-perm',
1740 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1742 'mustbeposted' => array(
1743 'code' => 'mustbeposted',
1744 'info' => "The \$1 module requires a POST request"
1748 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1750 'specialpage-cantexecute' => array(
1751 'code' => 'specialpage-cantexecute',
1752 'info' => "You don't have permission to view the results of this special page"
1754 'invalidoldimage' => array(
1755 'code' => 'invalidoldimage',
1756 'info' => 'The oldimage parameter has invalid format'
1758 'nodeleteablefile' => array(
1759 'code' => 'nodeleteablefile',
1760 'info' => 'No such old version of the file'
1762 'fileexists-forbidden' => array(
1763 'code' => 'fileexists-forbidden',
1764 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1766 'fileexists-shared-forbidden' => array(
1767 'code' => 'fileexists-shared-forbidden',
1768 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1770 'filerevert-badversion' => array(
1771 'code' => 'filerevert-badversion',
1772 'info' => 'There is no previous local version of this file with the provided timestamp.'
1775 // ApiEditPage messages
1776 'noimageredirect-anon' => array(
1777 'code' => 'noimageredirect-anon',
1778 'info' => "Anonymous users can't create image redirects"
1780 'noimageredirect-logged' => array(
1781 'code' => 'noimageredirect',
1782 'info' => "You don't have permission to create image redirects"
1784 'spamdetected' => array(
1785 'code' => 'spamdetected',
1786 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1788 'contenttoobig' => array(
1789 'code' => 'contenttoobig',
1790 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1792 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1793 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1794 'wasdeleted' => array(
1795 'code' => 'pagedeleted',
1796 'info' => "The page has been deleted since you fetched its timestamp"
1798 'blankpage' => array(
1799 'code' => 'emptypage',
1800 'info' => "Creating new, empty pages is not allowed"
1802 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1803 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1804 'missingtext' => array(
1806 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1808 'emptynewsection' => array(
1809 'code' => 'emptynewsection',
1810 'info' => 'Creating empty new sections is not possible.'
1812 'revwrongpage' => array(
1813 'code' => 'revwrongpage',
1814 'info' => "r\$1 is not a revision of \"\$2\""
1816 'undo-failure' => array(
1817 'code' => 'undofailure',
1818 'info' => 'Undo failed due to conflicting intermediate edits'
1821 // Messages from WikiPage::doEit()
1822 'edit-hook-aborted' => array(
1823 'code' => 'edit-hook-aborted',
1824 'info' => "Your edit was aborted by an ArticleSave hook"
1826 'edit-gone-missing' => array(
1827 'code' => 'edit-gone-missing',
1828 'info' => "The page you tried to edit doesn't seem to exist anymore"
1830 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1831 'edit-already-exists' => array(
1832 'code' => 'edit-already-exists',
1833 'info' => 'It seems the page you tried to create already exist'
1837 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1838 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1839 'uploaddisabled' => array(
1840 'code' => 'uploaddisabled',
1841 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1843 'copyuploaddisabled' => array(
1844 'code' => 'copyuploaddisabled',
1845 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1847 'copyuploadbaddomain' => array(
1848 'code' => 'copyuploadbaddomain',
1849 'info' => 'Uploads by URL are not allowed from this domain.'
1851 'copyuploadbadurl' => array(
1852 'code' => 'copyuploadbadurl',
1853 'info' => 'Upload not allowed from this URL.'
1856 'filename-tooshort' => array(
1857 'code' => 'filename-tooshort',
1858 'info' => 'The filename is too short'
1860 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1861 'illegal-filename' => array(
1862 'code' => 'illegal-filename',
1863 'info' => 'The filename is not allowed'
1865 'filetype-missing' => array(
1866 'code' => 'filetype-missing',
1867 'info' => 'The file is missing an extension'
1870 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1872 // @codingStandardsIgnoreEnd
1875 * Helper function for readonly errors
1877 public function dieReadOnly() {
1878 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1879 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1880 array( 'readonlyreason' => wfReadOnlyReason() ) );
1884 * Output the error message related to a certain array
1885 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1887 public function dieUsageMsg( $error ) {
1888 # most of the time we send a 1 element, so we might as well send it as
1889 # a string and make this an array here.
1890 if ( is_string( $error ) ) {
1891 $error = array( $error );
1893 $parsed = $this->parseMsg( $error );
1894 $this->dieUsage( $parsed['info'], $parsed['code'] );
1898 * Will only set a warning instead of failing if the global $wgDebugAPI
1899 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1900 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1903 public function dieUsageMsgOrDebug( $error ) {
1904 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1905 $this->dieUsageMsg( $error );
1908 if ( is_string( $error ) ) {
1909 $error = array( $error );
1911 $parsed = $this->parseMsg( $error );
1912 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1916 * Die with the $prefix.'badcontinue' error. This call is common enough to
1917 * make it into the base method.
1918 * @param bool $condition Will only die if this value is true
1921 protected function dieContinueUsageIf( $condition ) {
1924 'Invalid continue param. You should pass the original value returned by the previous query',
1930 * Return the error message related to a certain array
1931 * @param array $error Element of a getUserPermissionsErrors()-style array
1932 * @return array('code' => code, 'info' => info)
1934 public function parseMsg( $error ) {
1935 $error = (array)$error; // It seems strings sometimes make their way in here
1936 $key = array_shift( $error );
1938 // Check whether the error array was nested
1939 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1940 if ( is_array( $key ) ) {
1942 $key = array_shift( $error );
1945 if ( isset( self
::$messageMap[$key] ) ) {
1947 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1948 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1952 // If the key isn't present, throw an "unknown error"
1953 return $this->parseMsg( array( 'unknownerror', $key ) );
1957 * Internal code errors should be reported with this method
1958 * @param string $method Method or function name
1959 * @param string $message Error message
1960 * @throws MWException
1962 protected static function dieDebug( $method, $message ) {
1963 throw new MWException( "Internal error in $method: $message" );
1967 * Indicates if this module needs maxlag to be checked
1970 public function shouldCheckMaxlag() {
1975 * Indicates whether this module requires read rights
1978 public function isReadMode() {
1983 * Indicates whether this module requires write mode
1986 public function isWriteMode() {
1991 * Indicates whether this module must be called with a POST request
1994 public function mustBePosted() {
1999 * Returns whether this module requires a token to execute
2000 * It is used to show possible errors in action=paraminfo
2004 public function needsToken() {
2009 * Returns the token salt if there is one,
2010 * '' if the module doesn't require a salt,
2011 * else false if the module doesn't need a token
2012 * You have also to override needsToken()
2013 * Value is passed to User::getEditToken
2014 * @return bool|string|array
2016 public function getTokenSalt() {
2021 * Gets the user for whom to get the watchlist
2023 * @param array $params
2026 public function getWatchlistUser( $params ) {
2027 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2028 $user = User
::newFromName( $params['owner'], false );
2029 if ( !( $user && $user->getId() ) ) {
2030 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2032 $token = $user->getOption( 'watchlisttoken' );
2033 if ( $token == '' ||
$token != $params['token'] ) {
2035 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2040 if ( !$this->getUser()->isLoggedIn() ) {
2041 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2043 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2044 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2046 $user = $this->getUser();
2053 * @return bool|string|array Returns a false if the module has no help URL,
2054 * else returns a (array of) string
2056 public function getHelpUrls() {
2061 * This formerly attempted to return a list of all possible errors returned
2062 * by the module. However, this was impossible to maintain in many cases
2063 * since errors could come from other areas of MediaWiki and in some cases
2064 * from arbitrary extension hooks. Since a partial list claiming to be
2065 * comprehensive is unlikely to be useful, it was removed.
2067 * @deprecated since 1.24
2070 public function getPossibleErrors() {
2071 wfDeprecated( __METHOD__
, '1.24' );
2076 * @see self::getPossibleErrors()
2077 * @deprecated since 1.24
2080 public function getFinalPossibleErrors() {
2081 wfDeprecated( __METHOD__
, '1.24' );
2086 * @see self::getPossibleErrors()
2087 * @deprecated since 1.24
2090 public function parseErrors( $errors ) {
2091 wfDeprecated( __METHOD__
, '1.24' );
2096 * Profiling: total module execution time
2098 private $mTimeIn = 0, $mModuleTime = 0;
2101 * Start module profiling
2103 public function profileIn() {
2104 if ( $this->mTimeIn
!== 0 ) {
2105 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2107 $this->mTimeIn
= microtime( true );
2108 wfProfileIn( $this->getModuleProfileName() );
2112 * End module profiling
2114 public function profileOut() {
2115 if ( $this->mTimeIn
=== 0 ) {
2116 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2118 if ( $this->mDBTimeIn
!== 0 ) {
2121 'Must be called after database profiling is done with profileDBOut()'
2125 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2127 wfProfileOut( $this->getModuleProfileName() );
2131 * When modules crash, sometimes it is needed to do a profileOut() regardless
2132 * of the profiling state the module was in. This method does such cleanup.
2134 public function safeProfileOut() {
2135 if ( $this->mTimeIn
!== 0 ) {
2136 if ( $this->mDBTimeIn
!== 0 ) {
2137 $this->profileDBOut();
2139 $this->profileOut();
2144 * Total time the module was executed
2147 public function getProfileTime() {
2148 if ( $this->mTimeIn
!== 0 ) {
2149 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2152 return $this->mModuleTime
;
2156 * Profiling: database execution time
2158 private $mDBTimeIn = 0, $mDBTime = 0;
2161 * Start module profiling
2163 public function profileDBIn() {
2164 if ( $this->mTimeIn
=== 0 ) {
2167 'Must be called while profiling the entire module with profileIn()'
2170 if ( $this->mDBTimeIn
!== 0 ) {
2171 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2173 $this->mDBTimeIn
= microtime( true );
2174 wfProfileIn( $this->getModuleProfileName( true ) );
2178 * End database profiling
2180 public function profileDBOut() {
2181 if ( $this->mTimeIn
=== 0 ) {
2182 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2183 'the entire module with profileIn()' );
2185 if ( $this->mDBTimeIn
=== 0 ) {
2186 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2189 $time = microtime( true ) - $this->mDBTimeIn
;
2190 $this->mDBTimeIn
= 0;
2192 $this->mDBTime +
= $time;
2193 $this->getMain()->mDBTime +
= $time;
2194 wfProfileOut( $this->getModuleProfileName( true ) );
2198 * Total time the module used the database
2201 public function getProfileDBTime() {
2202 if ( $this->mDBTimeIn
!== 0 ) {
2203 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2206 return $this->mDBTime
;
2210 * Gets a default slave database connection object
2211 * @return DatabaseBase
2213 protected function getDB() {
2214 if ( !isset( $this->mSlaveDB
) ) {
2215 $this->profileDBIn();
2216 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2217 $this->profileDBOut();
2220 return $this->mSlaveDB
;
2224 * Debugging function that prints a value and an optional backtrace
2225 * @param mixed $value Value to print
2226 * @param string $name Description of the printed value
2227 * @param bool $backtrace If true, print a backtrace
2229 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2230 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2231 var_export( $value );
2233 print "\n" . wfBacktrace();
2239 * Write logging information for API features to a debug log, for usage
2241 * @param string $feature Feature being used.
2243 protected function logFeatureUsage( $feature ) {
2244 $request = $this->getRequest();
2246 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
2247 ' ' . $request->getIP() .
2248 ' "' . $request->getHeader( 'Referer' ) . '"' .
2249 ' "' . $request->getHeader( 'User-agent' ) . '"';
2250 wfDebugLog( 'api-feature-usage', $s, 'private' );