f776e6d4476861f935d2d26d6b1ebce937e690fd
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
{
44 // These constants allow modules to specify exactly how to treat incoming parameters.
46 const PARAM_DFLT
= 0; // Default value of the parameter
47 const PARAM_ISMULTI
= 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE
= 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX
= 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2
= 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN
= 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES
= 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED
= 7; // Boolean, is the parameter deprecated (will show a warning)
55 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
57 const PARAM_RANGE_ENFORCE
= 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
59 const PROP_ROOT
= 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
60 const PROP_LIST
= 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
61 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
62 const PROP_NULLABLE
= 1; // Boolean, can the property be not included in the result? Defaults to false
64 const LIMIT_BIG1
= 500; // Fast query, std user limit
65 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
66 const LIMIT_SML1
= 50; // Slow query, std user limit
67 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
70 * getAllowedParams() flag: When set, the result could take longer to generate,
71 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
74 const GET_VALUES_FOR_HELP
= 1;
76 private $mMainModule, $mModuleName, $mModulePrefix;
77 private $mSlaveDB = null;
78 private $mParamCache = array();
82 * @param $mainModule ApiMain object
83 * @param string $moduleName Name of this module
84 * @param string $modulePrefix Prefix to use for parameter names
86 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
87 $this->mMainModule
= $mainModule;
88 $this->mModuleName
= $moduleName;
89 $this->mModulePrefix
= $modulePrefix;
91 if ( !$this->isMain() ) {
92 $this->setContext( $mainModule->getContext() );
96 /*****************************************************************************
98 *****************************************************************************/
101 * Evaluates the parameters, performs the requested query, and sets up
102 * the result. Concrete implementations of ApiBase must override this
103 * method to provide whatever functionality their module offers.
104 * Implementations must not produce any output on their own and are not
105 * expected to handle any errors.
107 * The execute() method will be invoked directly by ApiMain immediately
108 * before the result of the module is output. Aside from the
109 * constructor, implementations should assume that no other methods
110 * will be called externally on the module before the result is
113 * The result data should be stored in the ApiResult object available
114 * through getResult().
116 abstract public function execute();
119 * Returns a string that identifies the version of the extending class.
120 * Typically includes the class name, the svn revision, timestamp, and
121 * last author. Usually done with SVN's Id keyword
123 * @deprecated since 1.21, version string is no longer supported
125 public function getVersion() {
126 wfDeprecated( __METHOD__
, '1.21' );
132 * Get the name of the module being executed by this instance
135 public function getModuleName() {
136 return $this->mModuleName
;
140 * Get the module manager, or null if this module has no sub-modules
142 * @return ApiModuleManager
144 public function getModuleManager() {
149 * Get parameter prefix (usually two letters or an empty string).
152 public function getModulePrefix() {
153 return $this->mModulePrefix
;
157 * Get the name of the module as shown in the profiler log
159 * @param $db DatabaseBase|bool
163 public function getModuleProfileName( $db = false ) {
165 return 'API:' . $this->mModuleName
. '-DB';
167 return 'API:' . $this->mModuleName
;
172 * Get the main module
173 * @return ApiMain object
175 public function getMain() {
176 return $this->mMainModule
;
180 * Returns true if this module is the main module ($this === $this->mMainModule),
184 public function isMain() {
185 return $this === $this->mMainModule
;
189 * Get the result object
192 public function getResult() {
193 // Main module has getResult() method overridden
194 // Safety - avoid infinite loop:
195 if ( $this->isMain() ) {
196 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
199 return $this->getMain()->getResult();
203 * Get the result data array (read-only)
206 public function getResultData() {
207 return $this->getResult()->getData();
211 * Create a new RequestContext object to use e.g. for calls to other parts
213 * The object will have the WebRequest and the User object set to the ones
214 * used in this instance.
216 * @deprecated since 1.19 use getContext to get the current context
217 * @return DerivativeContext
219 public function createContext() {
220 wfDeprecated( __METHOD__
, '1.19' );
222 return new DerivativeContext( $this->getContext() );
226 * Set warning section for this module. Users should monitor this
227 * section to notice any changes in API. Multiple calls to this
228 * function will result in the warning messages being separated by
230 * @param string $warning Warning message
232 public function setWarning( $warning ) {
233 $result = $this->getResult();
234 $data = $result->getData();
235 $moduleName = $this->getModuleName();
236 if ( isset( $data['warnings'][$moduleName] ) ) {
237 // Don't add duplicate warnings
238 $oldWarning = $data['warnings'][$moduleName]['*'];
239 $warnPos = strpos( $oldWarning, $warning );
240 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
241 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
242 // Check if $warning is followed by "\n" or the end of the $oldWarning
243 $warnPos +
= strlen( $warning );
244 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
248 // If there is a warning already, append it to the existing one
249 $warning = "$oldWarning\n$warning";
252 ApiResult
::setContent( $msg, $warning );
253 $result->disableSizeCheck();
254 $result->addValue( 'warnings', $moduleName,
255 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
256 $result->enableSizeCheck();
260 * If the module may only be used with a certain format module,
261 * it should override this method to return an instance of that formatter.
262 * A value of null means the default format will be used.
263 * @return mixed instance of a derived class of ApiFormatBase, or null
265 public function getCustomPrinter() {
270 * Generates help message for this module, or false if there is no description
271 * @return mixed string or false
273 public function makeHelpMsg() {
274 static $lnPrfx = "\n ";
276 $msg = $this->getFinalDescription();
278 if ( $msg !== false ) {
280 if ( !is_array( $msg ) ) {
285 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
287 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
289 if ( $this->isReadMode() ) {
290 $msg .= "\nThis module requires read rights";
292 if ( $this->isWriteMode() ) {
293 $msg .= "\nThis module requires write rights";
295 if ( $this->mustBePosted() ) {
296 $msg .= "\nThis module only accepts POST requests";
298 if ( $this->isReadMode() ||
$this->isWriteMode() ||
299 $this->mustBePosted()
305 $paramsMsg = $this->makeHelpMsgParameters();
306 if ( $paramsMsg !== false ) {
307 $msg .= "Parameters:\n$paramsMsg";
310 $examples = $this->getExamples();
312 if ( !is_array( $examples ) ) {
317 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
318 foreach ( $examples as $k => $v ) {
319 if ( is_numeric( $k ) ) {
322 if ( is_array( $v ) ) {
323 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
328 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
338 * @param $item string
341 private function indentExampleText( $item ) {
346 * @param string $prefix Text to split output items
347 * @param string $title What is being output
348 * @param $input string|array
351 protected function makeHelpArrayToString( $prefix, $title, $input ) {
352 if ( $input === false ) {
355 if ( !is_array( $input ) ) {
356 $input = array( $input );
359 if ( count( $input ) > 0 ) {
361 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
365 $msg .= implode( $prefix, $input ) . "\n";
374 * Generates the parameter descriptions for this module, to be displayed in the
376 * @return string or false
378 public function makeHelpMsgParameters() {
379 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
382 $paramsDescription = $this->getFinalParamDescription();
384 $paramPrefix = "\n" . str_repeat( ' ', 24 );
385 $descWordwrap = "\n" . str_repeat( ' ', 28 );
386 foreach ( $params as $paramName => $paramSettings ) {
387 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
388 if ( is_array( $desc ) ) {
389 $desc = implode( $paramPrefix, $desc );
393 if ( !is_array( $paramSettings ) ) {
394 $paramSettings = array(
395 self
::PARAM_DFLT
=> $paramSettings,
399 //handle missing type
400 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
401 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] ) ?
$paramSettings[ApiBase
::PARAM_DFLT
] : null;
402 if ( is_bool( $dflt ) ) {
403 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
404 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
405 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
406 } elseif ( is_int( $dflt ) ) {
407 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
411 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] ) && $paramSettings[self
::PARAM_DEPRECATED
] ) {
412 $desc = "DEPRECATED! $desc";
415 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] ) && $paramSettings[self
::PARAM_REQUIRED
] ) {
416 $desc .= $paramPrefix . "This parameter is required";
419 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
420 if ( isset( $type ) ) {
421 $hintPipeSeparated = true;
422 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
424 $prompt = 'Values (separate with \'|\'): ';
426 $prompt = 'One value: ';
429 if ( is_array( $type ) ) {
432 foreach ( $type as $t ) {
434 $nothingPrompt = 'Can be empty, or ';
439 $desc .= $paramPrefix . $nothingPrompt . $prompt;
440 $choicesstring = implode( ', ', $choices );
441 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
442 $hintPipeSeparated = false;
446 // Special handling because namespaces are type-limited, yet they are not given
447 $desc .= $paramPrefix . $prompt;
448 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
449 100, $descWordwrap );
450 $hintPipeSeparated = false;
453 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
454 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
455 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
460 $s = $multi ?
's' : '';
461 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
462 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
463 if ( $hasMin ||
$hasMax ) {
465 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
466 } elseif ( !$hasMin ) {
467 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
469 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
472 $desc .= $paramPrefix . $intRangeStr;
476 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
482 if ( $hintPipeSeparated ) {
483 $desc .= $paramPrefix . "Separate values with '|'";
486 $isArray = is_array( $type );
488 ||
$isArray && count( $type ) > self
::LIMIT_SML1
490 $desc .= $paramPrefix . "Maximum number of values " .
491 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
496 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
497 if ( !is_null( $default ) && $default !== false ) {
498 $desc .= $paramPrefix . "Default: $default";
501 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
511 * Returns the description string for this module
512 * @return mixed string or array of strings
514 protected function getDescription() {
519 * Returns usage examples for this module. Return false if no examples are available.
520 * @return bool|string|array
522 protected function getExamples() {
527 * Returns an array of allowed parameters (parameter name) => (default
528 * value) or (parameter name) => (array with PARAM_* constants as keys)
529 * Don't call this function directly: use getFinalParams() to allow
530 * hooks to modify parameters as needed.
532 * Some derived classes may choose to handle an integer $flags parameter
533 * in the overriding methods. Callers of this method can pass zero or
534 * more OR-ed flags like GET_VALUES_FOR_HELP.
538 protected function getAllowedParams( /* $flags = 0 */ ) {
539 // int $flags is not declared because it causes "Strict standards"
540 // warning. Most derived classes do not implement it.
545 * Returns an array of parameter descriptions.
546 * Don't call this function directly: use getFinalParamDescription() to
547 * allow hooks to modify descriptions as needed.
548 * @return array|bool False on no parameter descriptions
550 protected function getParamDescription() {
555 * Get final list of parameters, after hooks have had a chance to
556 * tweak it as needed.
558 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
559 * @return array|Bool False on no parameters
560 * @since 1.21 $flags param added
562 public function getFinalParams( $flags = 0 ) {
563 $params = $this->getAllowedParams( $flags );
564 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
570 * Get final parameter descriptions, after hooks have had a chance to tweak it as
573 * @return array|bool False on no parameter descriptions
575 public function getFinalParamDescription() {
576 $desc = $this->getParamDescription();
577 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
583 * Returns possible properties in the result, grouped by the value of the prop parameter
586 * Properties that are shown always are in a group with empty string as a key.
587 * Properties that can be shown by several values of prop are included multiple times.
588 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
589 * those on the root object are under the key PROP_ROOT.
590 * The array can also contain a boolean under the key PROP_LIST,
591 * indicating whether the result is a list.
593 * Don't call this function directly: use getFinalResultProperties() to
594 * allow hooks to modify descriptions as needed.
596 * @return array|bool False on no properties
598 protected function getResultProperties() {
603 * Get final possible result properties, after hooks have had a chance to tweak it as
608 public function getFinalResultProperties() {
609 $properties = $this->getResultProperties();
610 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
616 * Add token properties to the array used by getResultProperties,
617 * based on a token functions mapping.
619 protected static function addTokenProperties( &$props, $tokenFunctions ) {
620 foreach ( array_keys( $tokenFunctions ) as $token ) {
621 $props[''][$token . 'token'] = array(
622 ApiBase
::PROP_TYPE
=> 'string',
623 ApiBase
::PROP_NULLABLE
=> true
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 $parseLimit Boolean: 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.
693 * @param array $params of parameter names
695 public function requireOnlyOneParameter( $params ) {
696 $required = func_get_args();
697 array_shift( $required );
698 $p = $this->getModulePrefix();
700 $intersection = array_intersect( array_keys( array_filter( $params,
701 array( $this, "parameterNotEmpty" ) ) ), $required );
703 if ( count( $intersection ) > 1 ) {
704 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', 'invalidparammix' );
705 } elseif ( count( $intersection ) == 0 ) {
706 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', 'missingparam' );
711 * Generates the possible errors requireOnlyOneParameter() can die with
713 * @param $params array
716 public function getRequireOnlyOneParameterErrorMessages( $params ) {
717 $p = $this->getModulePrefix();
718 $params = implode( ", {$p}", $params );
721 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
722 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
727 * Die if more than one of a certain set of parameters is set and not false.
729 * @param $params array
731 public function requireMaxOneParameter( $params ) {
732 $required = func_get_args();
733 array_shift( $required );
734 $p = $this->getModulePrefix();
736 $intersection = array_intersect( array_keys( array_filter( $params,
737 array( $this, "parameterNotEmpty" ) ) ), $required );
739 if ( count( $intersection ) > 1 ) {
740 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', 'invalidparammix' );
745 * Generates the possible error requireMaxOneParameter() can die with
747 * @param $params array
750 public function getRequireMaxOneParameterErrorMessages( $params ) {
751 $p = $this->getModulePrefix();
752 $params = implode( ", {$p}", $params );
755 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
760 * @param $params array
761 * @param bool|string $load Whether load the object's state from the database:
762 * - false: don't load (if the pageid is given, it will still be loaded)
763 * - 'fromdb': load from a slave database
764 * - 'fromdbmaster': load from the master database
767 public function getTitleOrPageId( $params, $load = false ) {
768 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
771 if ( isset( $params['title'] ) ) {
772 $titleObj = Title
::newFromText( $params['title'] );
773 if ( !$titleObj ||
$titleObj->isExternal() ) {
774 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
776 if ( !$titleObj->canExist() ) {
777 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
779 $pageObj = WikiPage
::factory( $titleObj );
780 if ( $load !== false ) {
781 $pageObj->loadPageData( $load );
783 } elseif ( isset( $params['pageid'] ) ) {
784 if ( $load === false ) {
787 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
789 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
799 public function getTitleOrPageIdErrorMessage() {
801 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
803 array( 'invalidtitle', 'title' ),
804 array( 'nosuchpageid', 'pageid' ),
810 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
812 * @param $x object Parameter to check is not null/false
815 private function parameterNotEmpty( $x ) {
816 return !is_null( $x ) && $x !== false;
820 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
824 public static function getValidNamespaces() {
825 wfDeprecated( __METHOD__
, '1.17' );
827 return MWNamespace
::getValidNamespaces();
831 * Return true if we're to watch the page, false if not, null if no change.
832 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
833 * @param $titleObj Title the page under consideration
834 * @param string $userOption The user option to consider when $watchlist=preferences.
835 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
838 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
840 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
842 switch ( $watchlist ) {
850 # If the user is already watching, don't bother checking
851 if ( $userWatching ) {
854 # If no user option was passed, use watchdefault and watchcreations
855 if ( is_null( $userOption ) ) {
856 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
857 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
860 # Watch the article based on the user preference
861 return $this->getUser()->getBoolOption( $userOption );
864 return $userWatching;
867 return $userWatching;
872 * Set a watch (or unwatch) based the based on a watchlist parameter.
873 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
874 * @param $titleObj Title the article's title to change
875 * @param string $userOption The user option to consider when $watch=preferences
877 protected function setWatch( $watch, $titleObj, $userOption = null ) {
878 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
879 if ( $value === null ) {
883 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
887 * Using the settings determine the value for the given parameter
889 * @param string $paramName parameter name
890 * @param array|mixed $paramSettings default value or an array of settings
891 * using PARAM_* constants.
892 * @param $parseLimit Boolean: parse limit?
893 * @return mixed Parameter value
895 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
896 // Some classes may decide to change parameter names
897 $encParamName = $this->encodeParamName( $paramName );
899 if ( !is_array( $paramSettings ) ) {
900 $default = $paramSettings;
902 $type = gettype( $paramSettings );
907 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
908 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
909 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
910 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
911 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
912 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
914 // When type is not given, and no choices, the type is the same as $default
915 if ( !isset( $type ) ) {
916 if ( isset( $default ) ) {
917 $type = gettype( $default );
919 $type = 'NULL'; // allow everything
924 if ( $type == 'boolean' ) {
925 if ( isset( $default ) && $default !== false ) {
926 // Having a default value of anything other than 'false' is not allowed
927 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
930 $value = $this->getMain()->getCheck( $encParamName );
931 } elseif ( $type == 'upload' ) {
932 if ( isset( $default ) ) {
933 // Having a default value is not allowed
934 ApiBase
::dieDebug( __METHOD__
, "File upload param $encParamName's default is set to '$default'. File upload parameters may not have a default." );
937 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
939 $value = $this->getMain()->getUpload( $encParamName );
940 if ( !$value->exists() ) {
941 // This will get the value without trying to normalize it
942 // (because trying to normalize a large binary file
943 // accidentally uploaded as a field fails spectacularly)
944 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
945 if ( $value !== null ) {
947 "File upload param $encParamName is not a file upload; " .
948 "be sure to use multipart/form-data for your POST and include " .
949 "a filename in the Content-Disposition header.",
950 "badupload_{$encParamName}"
955 $value = $this->getMain()->getVal( $encParamName, $default );
957 if ( isset( $value ) && $type == 'namespace' ) {
958 $type = MWNamespace
::getValidNamespaces();
962 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
963 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
966 // More validation only when choices were not given
967 // choices were validated in parseMultiValue()
968 if ( isset( $value ) ) {
969 if ( !is_array( $type ) ) {
971 case 'NULL': // nothing to do
974 if ( $required && $value === '' ) {
975 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
978 case 'integer': // Force everything using intval() and optionally validate limits
979 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
980 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
981 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
982 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
984 if ( is_array( $value ) ) {
985 $value = array_map( 'intval', $value );
986 if ( !is_null( $min ) ||
!is_null( $max ) ) {
987 foreach ( $value as &$v ) {
988 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
992 $value = intval( $value );
993 if ( !is_null( $min ) ||
!is_null( $max ) ) {
994 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
999 if ( !$parseLimit ) {
1000 // Don't do any validation whatsoever
1003 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
1004 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
1007 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1009 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1010 if ( $value == 'max' ) {
1011 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
1012 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1014 $value = intval( $value );
1015 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
1020 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1024 if ( is_array( $value ) ) {
1025 foreach ( $value as $key => $val ) {
1026 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1029 $value = $this->validateTimestamp( $value, $encParamName );
1033 if ( is_array( $value ) ) {
1034 foreach ( $value as $key => $val ) {
1035 $value[$key] = $this->validateUser( $val, $encParamName );
1038 $value = $this->validateUser( $value, $encParamName );
1041 case 'upload': // nothing to do
1044 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1048 // Throw out duplicates if requested
1049 if ( !$dupes && is_array( $value ) ) {
1050 $value = array_unique( $value );
1053 // Set a warning if a deprecated parameter has been passed
1054 if ( $deprecated && $value !== false ) {
1055 $this->setWarning( "The $encParamName parameter has been deprecated." );
1057 } elseif ( $required ) {
1058 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1065 * Return an array of values that were given in a 'a|b|c' notation,
1066 * after it optionally validates them against the list allowed values.
1068 * @param string $valueName The name of the parameter (for error
1070 * @param $value mixed The value being parsed
1071 * @param bool $allowMultiple Can $value contain more than one value
1073 * @param $allowedValues mixed An array of values to check against. If
1074 * null, all values are accepted.
1075 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1077 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1078 if ( trim( $value ) === '' && $allowMultiple ) {
1082 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1083 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1084 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
1085 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
1087 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1088 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1091 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1092 // Bug 33482 - Allow entries with | in them for non-multiple values
1093 if ( in_array( $value, $allowedValues, true ) ) {
1097 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
1098 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1101 if ( is_array( $allowedValues ) ) {
1102 // Check for unknown values
1103 $unknown = array_diff( $valuesList, $allowedValues );
1104 if ( count( $unknown ) ) {
1105 if ( $allowMultiple ) {
1106 $s = count( $unknown ) > 1 ?
's' : '';
1107 $vals = implode( ", ", $unknown );
1108 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1110 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1113 // Now throw them out
1114 $valuesList = array_intersect( $valuesList, $allowedValues );
1117 return $allowMultiple ?
$valuesList : $valuesList[0];
1121 * Validate the value against the minimum and user/bot maximum limits.
1122 * Prints usage info on failure.
1123 * @param string $paramName Parameter name
1124 * @param int $value Parameter value
1125 * @param int|null $min Minimum value
1126 * @param int|null $max Maximum value for users
1127 * @param int $botMax Maximum value for sysops/bots
1128 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1130 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1131 if ( !is_null( $min ) && $value < $min ) {
1133 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1134 $this->warnOrDie( $msg, $enforceLimits );
1138 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1139 if ( $this->getMain()->isInternalMode() ) {
1143 // Optimization: do not check user's bot status unless really needed -- skips db query
1144 // assumes $botMax >= $max
1145 if ( !is_null( $max ) && $value > $max ) {
1146 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1147 if ( $value > $botMax ) {
1148 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1149 $this->warnOrDie( $msg, $enforceLimits );
1153 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1154 $this->warnOrDie( $msg, $enforceLimits );
1161 * Validate and normalize of parameters of type 'timestamp'
1162 * @param string $value Parameter value
1163 * @param string $encParamName Parameter name
1164 * @return string Validated and normalized parameter
1166 function validateTimestamp( $value, $encParamName ) {
1167 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1168 if ( $unixTimestamp === false ) {
1169 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
1172 return wfTimestamp( TS_MW
, $unixTimestamp );
1176 * Validate and normalize of parameters of type 'user'
1177 * @param string $value Parameter value
1178 * @param string $encParamName Parameter name
1179 * @return string Validated and normalized parameter
1181 private function validateUser( $value, $encParamName ) {
1182 $title = Title
::makeTitleSafe( NS_USER
, $value );
1183 if ( $title === null ) {
1184 $this->dieUsage( "Invalid value '$value' for user parameter $encParamName", "baduser_{$encParamName}" );
1187 return $title->getText();
1191 * Adds a warning to the output, else dies
1193 * @param $msg String Message to show as a warning, or error message if dying
1194 * @param $enforceLimits Boolean Whether this is an enforce (die)
1196 private function warnOrDie( $msg, $enforceLimits = false ) {
1197 if ( $enforceLimits ) {
1198 $this->dieUsage( $msg, 'integeroutofrange' );
1200 $this->setWarning( $msg );
1205 * Truncate an array to a certain length.
1206 * @param array $arr Array to truncate
1207 * @param int $limit Maximum length
1208 * @return bool True if the array was truncated, false otherwise
1210 public static function truncateArray( &$arr, $limit ) {
1212 while ( count( $arr ) > $limit ) {
1221 * Throw a UsageException, which will (if uncaught) call the main module's
1222 * error handler and die with an error message.
1224 * @param string $description One-line human-readable description of the
1225 * error condition, e.g., "The API requires a valid action parameter"
1226 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1227 * automated identification of the error, e.g., 'unknown_action'
1228 * @param int $httpRespCode HTTP response code
1229 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1230 * @throws UsageException
1232 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1233 Profiler
::instance()->close();
1234 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1238 * Throw a UsageException based on the errors in the Status object.
1241 * @param Status $status Status object
1242 * @throws UsageException
1244 public function dieStatus( $status ) {
1245 if ( $status->isGood() ) {
1246 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1249 $errors = $status->getErrorsArray();
1251 // No errors? Assume the warnings should be treated as errors
1252 $errors = $status->getWarningsArray();
1255 // Still no errors? Punt
1256 $errors = array( array( 'unknownerror-nocode' ) );
1259 // Cannot use dieUsageMsg() because extensions might return custom
1261 if ( $errors[0] instanceof Message
) {
1263 $code = $msg->getKey();
1265 $code = array_shift( $errors[0] );
1266 $msg = wfMessage( $code, $errors[0] );
1268 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1269 // Translate message to code, for backwards compatability
1270 $code = ApiBase
::$messageMap[$code]['code'];
1272 $this->dieUsage( $msg->inLanguage( 'en' )->useDatabase( false )->plain(), $code );
1276 * Array that maps message keys to error messages. $1 and friends are replaced.
1278 public static $messageMap = array(
1279 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1280 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1281 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1283 // Messages from Title::getUserPermissionsErrors()
1284 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1285 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1286 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1287 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1288 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1289 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1290 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1291 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1292 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1293 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1294 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1295 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1296 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1297 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1298 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1299 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your email address before you can edit" ),
1300 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1301 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1303 // Miscellaneous interface messages
1304 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1305 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1306 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1307 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1308 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1309 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1310 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1311 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1312 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1313 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1314 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1315 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1316 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1317 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1318 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1319 // 'badarticleerror' => shouldn't happen
1320 // 'badtitletext' => shouldn't happen
1321 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1322 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1323 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1324 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1325 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1326 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1327 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', '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." ),
1328 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1329 'mailnologin' => array( 'code' => 'cantsend', '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" ),
1330 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1331 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1332 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1333 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending email" ),
1334 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1335 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" ),
1336 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1337 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1338 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1339 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1340 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1341 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1342 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1343 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1344 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1345 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1346 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1348 // API-specific messages
1349 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1350 'writedisabled' => array( 'code' => 'noapiwrite', '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" ),
1351 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1352 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1353 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1354 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1355 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1356 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1357 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1358 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1359 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1360 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1361 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1362 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1363 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1364 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending email through the wiki" ),
1365 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1366 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1367 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1368 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1369 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1370 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1371 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1372 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1373 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1374 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1375 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1376 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1377 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1378 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1379 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1380 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1381 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1382 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1383 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1384 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1385 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1386 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1387 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1388 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1389 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1390 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1391 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1392 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1393 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1394 'fileexists-shared-forbidden' => array( 'code' => 'fileexists-shared-forbidden', 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' ),
1395 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1397 // ApiEditPage messages
1398 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1399 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1400 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1401 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1402 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1403 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1404 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1405 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1406 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1407 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1408 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1409 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1410 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1411 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1413 // Messages from WikiPage::doEit()
1414 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1415 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1416 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1417 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1420 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1421 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1422 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ),
1423 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1424 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1425 'copyuploadbadurl' => array( 'code' => 'copyuploadbadurl', 'info' => 'Upload not allowed from this URL.' ),
1427 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1428 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1429 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1430 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1432 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1436 * Helper function for readonly errors
1438 public function dieReadOnly() {
1439 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1440 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1441 array( 'readonlyreason' => wfReadOnlyReason() ) );
1445 * Output the error message related to a certain array
1446 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1448 public function dieUsageMsg( $error ) {
1449 # most of the time we send a 1 element, so we might as well send it as
1450 # a string and make this an array here.
1451 if ( is_string( $error ) ) {
1452 $error = array( $error );
1454 $parsed = $this->parseMsg( $error );
1455 $this->dieUsage( $parsed['info'], $parsed['code'] );
1459 * Will only set a warning instead of failing if the global $wgDebugAPI
1460 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1461 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1464 public function dieUsageMsgOrDebug( $error ) {
1466 if ( $wgDebugAPI !== true ) {
1467 $this->dieUsageMsg( $error );
1469 if ( is_string( $error ) ) {
1470 $error = array( $error );
1472 $parsed = $this->parseMsg( $error );
1473 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1474 . ' - ' . $parsed['info'] );
1479 * Die with the $prefix.'badcontinue' error. This call is common enough to make it into the base method.
1480 * @param $condition boolean will only die if this value is true
1483 protected function dieContinueUsageIf( $condition ) {
1486 'Invalid continue param. You should pass the original value returned by the previous query',
1492 * Return the error message related to a certain array
1493 * @param array $error Element of a getUserPermissionsErrors()-style array
1494 * @return array('code' => code, 'info' => info)
1496 public function parseMsg( $error ) {
1497 $error = (array)$error; // It seems strings sometimes make their way in here
1498 $key = array_shift( $error );
1500 // Check whether the error array was nested
1501 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1502 if ( is_array( $key ) ) {
1504 $key = array_shift( $error );
1507 if ( isset( self
::$messageMap[$key] ) ) {
1509 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1510 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1514 // If the key isn't present, throw an "unknown error"
1515 return $this->parseMsg( array( 'unknownerror', $key ) );
1519 * Internal code errors should be reported with this method
1520 * @param string $method Method or function name
1521 * @param string $message Error message
1523 protected static function dieDebug( $method, $message ) {
1524 throw new MWException( "Internal error in $method: $message" );
1528 * Indicates if this module needs maxlag to be checked
1531 public function shouldCheckMaxlag() {
1536 * Indicates whether this module requires read rights
1539 public function isReadMode() {
1544 * Indicates whether this module requires write mode
1547 public function isWriteMode() {
1552 * Indicates whether this module must be called with a POST request
1555 public function mustBePosted() {
1560 * Returns whether this module requires a token to execute
1561 * It is used to show possible errors in action=paraminfo
1565 public function needsToken() {
1570 * Returns the token salt if there is one,
1571 * '' if the module doesn't require a salt,
1572 * else false if the module doesn't need a token
1573 * You have also to override needsToken()
1574 * Value is passed to User::getEditToken
1575 * @return bool|string|array
1577 public function getTokenSalt() {
1582 * Gets the user for whom to get the watchlist
1584 * @param $params array
1587 public function getWatchlistUser( $params ) {
1588 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1589 $user = User
::newFromName( $params['owner'], false );
1590 if ( !( $user && $user->getId() ) ) {
1591 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1593 $token = $user->getOption( 'watchlisttoken' );
1594 if ( $token == '' ||
$token != $params['token'] ) {
1595 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1598 if ( !$this->getUser()->isLoggedIn() ) {
1599 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1601 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1602 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1604 $user = $this->getUser();
1611 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1613 public function getHelpUrls() {
1618 * Returns a list of all possible errors returned by the module
1620 * Don't call this function directly: use getFinalPossibleErrors() to allow
1621 * hooks to modify parameters as needed.
1623 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1625 public function getPossibleErrors() {
1628 $params = $this->getFinalParams();
1630 foreach ( $params as $paramName => $paramSettings ) {
1631 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) && $paramSettings[ApiBase
::PARAM_REQUIRED
] ) {
1632 $ret[] = array( 'missingparam', $paramName );
1635 if ( array_key_exists( 'continue', $params ) ) {
1637 'code' => 'badcontinue',
1638 'info' => 'Invalid continue param. You should pass the original value returned by the previous query'
1643 if ( $this->mustBePosted() ) {
1644 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1647 if ( $this->isReadMode() ) {
1648 $ret[] = array( 'readrequired' );
1651 if ( $this->isWriteMode() ) {
1652 $ret[] = array( 'writerequired' );
1653 $ret[] = array( 'writedisabled' );
1656 if ( $this->needsToken() ) {
1657 if ( !isset( $params['token'][ApiBase
::PARAM_REQUIRED
] )
1658 ||
!$params['token'][ApiBase
::PARAM_REQUIRED
]
1660 // Add token as possible missing parameter, if not already done
1661 $ret[] = array( 'missingparam', 'token' );
1663 $ret[] = array( 'sessionfailure' );
1670 * Get final list of possible errors, after hooks have had a chance to
1671 * tweak it as needed.
1676 public function getFinalPossibleErrors() {
1677 $possibleErrors = $this->getPossibleErrors();
1678 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
1680 return $possibleErrors;
1684 * Parses a list of errors into a standardised format
1685 * @param array $errors List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1686 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1688 public function parseErrors( $errors ) {
1691 foreach ( $errors as $row ) {
1692 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1695 $ret[] = $this->parseMsg( $row );
1703 * Profiling: total module execution time
1705 private $mTimeIn = 0, $mModuleTime = 0;
1708 * Start module profiling
1710 public function profileIn() {
1711 if ( $this->mTimeIn
!== 0 ) {
1712 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1714 $this->mTimeIn
= microtime( true );
1715 wfProfileIn( $this->getModuleProfileName() );
1719 * End module profiling
1721 public function profileOut() {
1722 if ( $this->mTimeIn
=== 0 ) {
1723 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1725 if ( $this->mDBTimeIn
!== 0 ) {
1726 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1729 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1731 wfProfileOut( $this->getModuleProfileName() );
1735 * When modules crash, sometimes it is needed to do a profileOut() regardless
1736 * of the profiling state the module was in. This method does such cleanup.
1738 public function safeProfileOut() {
1739 if ( $this->mTimeIn
!== 0 ) {
1740 if ( $this->mDBTimeIn
!== 0 ) {
1741 $this->profileDBOut();
1743 $this->profileOut();
1748 * Total time the module was executed
1751 public function getProfileTime() {
1752 if ( $this->mTimeIn
!== 0 ) {
1753 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1756 return $this->mModuleTime
;
1760 * Profiling: database execution time
1762 private $mDBTimeIn = 0, $mDBTime = 0;
1765 * Start module profiling
1767 public function profileDBIn() {
1768 if ( $this->mTimeIn
=== 0 ) {
1769 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1771 if ( $this->mDBTimeIn
!== 0 ) {
1772 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1774 $this->mDBTimeIn
= microtime( true );
1775 wfProfileIn( $this->getModuleProfileName( true ) );
1779 * End database profiling
1781 public function profileDBOut() {
1782 if ( $this->mTimeIn
=== 0 ) {
1783 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1785 if ( $this->mDBTimeIn
=== 0 ) {
1786 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1789 $time = microtime( true ) - $this->mDBTimeIn
;
1790 $this->mDBTimeIn
= 0;
1792 $this->mDBTime +
= $time;
1793 $this->getMain()->mDBTime +
= $time;
1794 wfProfileOut( $this->getModuleProfileName( true ) );
1798 * Total time the module used the database
1801 public function getProfileDBTime() {
1802 if ( $this->mDBTimeIn
!== 0 ) {
1803 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1806 return $this->mDBTime
;
1810 * Gets a default slave database connection object
1811 * @return DatabaseBase
1813 protected function getDB() {
1814 if ( !isset( $this->mSlaveDB
) ) {
1815 $this->profileDBIn();
1816 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
1817 $this->profileDBOut();
1820 return $this->mSlaveDB
;
1824 * Debugging function that prints a value and an optional backtrace
1825 * @param $value mixed Value to print
1826 * @param string $name Description of the printed value
1827 * @param bool $backtrace If true, print a backtrace
1829 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1830 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1831 var_export( $value );
1833 print "\n" . wfBacktrace();