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
69 private $mMainModule, $mModuleName, $mModulePrefix;
70 private $mParamCache = array();
74 * @param $mainModule ApiMain object
75 * @param $moduleName string Name of this module
76 * @param $modulePrefix string Prefix to use for parameter names
78 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
79 $this->mMainModule
= $mainModule;
80 $this->mModuleName
= $moduleName;
81 $this->mModulePrefix
= $modulePrefix;
83 if ( !$this->isMain() ) {
84 $this->setContext( $mainModule->getContext() );
88 /*****************************************************************************
90 *****************************************************************************/
93 * Evaluates the parameters, performs the requested query, and sets up
94 * the result. Concrete implementations of ApiBase must override this
95 * method to provide whatever functionality their module offers.
96 * Implementations must not produce any output on their own and are not
97 * expected to handle any errors.
99 * The execute() method will be invoked directly by ApiMain immediately
100 * before the result of the module is output. Aside from the
101 * constructor, implementations should assume that no other methods
102 * will be called externally on the module before the result is
105 * The result data should be stored in the ApiResult object available
106 * through getResult().
108 abstract public function execute();
111 * Returns a string that identifies the version of the extending class.
112 * Typically includes the class name, the svn revision, timestamp, and
113 * last author. Usually done with SVN's Id keyword
115 * @deprecated since 1.21, version string is no longer supported
117 public function getVersion() {
118 wfDeprecated( __METHOD__
, '1.21' );
123 * Get the name of the module being executed by this instance
126 public function getModuleName() {
127 return $this->mModuleName
;
132 * Get the module manager, or null if this module has no sub-modules
134 * @return ApiModuleManager
136 public function getModuleManager() {
141 * Get parameter prefix (usually two letters or an empty string).
144 public function getModulePrefix() {
145 return $this->mModulePrefix
;
149 * Get the name of the module as shown in the profiler log
151 * @param $db DatabaseBase|bool
155 public function getModuleProfileName( $db = false ) {
157 return 'API:' . $this->mModuleName
. '-DB';
159 return 'API:' . $this->mModuleName
;
164 * Get the main module
165 * @return ApiMain object
167 public function getMain() {
168 return $this->mMainModule
;
172 * Returns true if this module is the main module ($this === $this->mMainModule),
176 public function isMain() {
177 return $this === $this->mMainModule
;
181 * Get the result object
184 public function getResult() {
185 // Main module has getResult() method overriden
186 // Safety - avoid infinite loop:
187 if ( $this->isMain() ) {
188 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
190 return $this->getMain()->getResult();
194 * Get the result data array (read-only)
197 public function getResultData() {
198 return $this->getResult()->getData();
202 * Create a new RequestContext object to use e.g. for calls to other parts
204 * The object will have the WebRequest and the User object set to the ones
205 * used in this instance.
207 * @deprecated since 1.19 use getContext to get the current context
208 * @return DerivativeContext
210 public function createContext() {
211 wfDeprecated( __METHOD__
, '1.19' );
212 return new DerivativeContext( $this->getContext() );
216 * Set warning section for this module. Users should monitor this
217 * section to notice any changes in API. Multiple calls to this
218 * function will result in the warning messages being separated by
220 * @param $warning string Warning message
222 public function setWarning( $warning ) {
223 $result = $this->getResult();
224 $data = $result->getData();
225 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
226 // Don't add duplicate warnings
227 $warn_regex = preg_quote( $warning, '/' );
228 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
231 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
232 // If there is a warning already, append it to the existing one
233 $warning = "$oldwarning\n$warning";
234 $result->unsetValue( 'warnings', $this->getModuleName() );
237 ApiResult
::setContent( $msg, $warning );
238 $result->disableSizeCheck();
239 $result->addValue( 'warnings', $this->getModuleName(), $msg );
240 $result->enableSizeCheck();
244 * If the module may only be used with a certain format module,
245 * it should override this method to return an instance of that formatter.
246 * A value of null means the default format will be used.
247 * @return mixed instance of a derived class of ApiFormatBase, or null
249 public function getCustomPrinter() {
254 * Generates help message for this module, or false if there is no description
255 * @return mixed string or false
257 public function makeHelpMsg() {
258 static $lnPrfx = "\n ";
260 $msg = $this->getFinalDescription();
262 if ( $msg !== false ) {
264 if ( !is_array( $msg ) ) {
269 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
271 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
273 if ( $this->isReadMode() ) {
274 $msg .= "\nThis module requires read rights";
276 if ( $this->isWriteMode() ) {
277 $msg .= "\nThis module requires write rights";
279 if ( $this->mustBePosted() ) {
280 $msg .= "\nThis module only accepts POST requests";
282 if ( $this->isReadMode() ||
$this->isWriteMode() ||
283 $this->mustBePosted() ) {
288 $paramsMsg = $this->makeHelpMsgParameters();
289 if ( $paramsMsg !== false ) {
290 $msg .= "Parameters:\n$paramsMsg";
293 $examples = $this->getExamples();
294 if ( $examples !== false && $examples !== '' ) {
295 if ( !is_array( $examples ) ) {
300 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
301 foreach( $examples as $k => $v ) {
303 if ( is_numeric( $k ) ) {
306 if ( is_array( $v ) ) {
307 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
312 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
322 * @param $item string
325 private function indentExampleText( $item ) {
330 * @param $prefix string Text to split output items
331 * @param $title string What is being output
332 * @param $input string|array
335 protected function makeHelpArrayToString( $prefix, $title, $input ) {
336 if ( $input === false ) {
339 if ( !is_array( $input ) ) {
340 $input = array( $input );
343 if ( count( $input ) > 0 ) {
345 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
349 $msg .= implode( $prefix, $input ) . "\n";
356 * Generates the parameter descriptions for this module, to be displayed in the
358 * @return string or false
360 public function makeHelpMsgParameters() {
361 $params = $this->getFinalParams();
364 $paramsDescription = $this->getFinalParamDescription();
366 $paramPrefix = "\n" . str_repeat( ' ', 24 );
367 $descWordwrap = "\n" . str_repeat( ' ', 28 );
368 foreach ( $params as $paramName => $paramSettings ) {
369 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
370 if ( is_array( $desc ) ) {
371 $desc = implode( $paramPrefix, $desc );
375 if ( !is_array( $paramSettings ) ) {
376 $paramSettings = array(
377 self
::PARAM_DFLT
=> $paramSettings,
381 //handle missing type
382 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
383 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] ) ?
$paramSettings[ApiBase
::PARAM_DFLT
] : null;
384 if ( is_bool( $dflt ) ) {
385 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
386 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
387 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
388 } elseif ( is_int( $dflt ) ) {
389 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
393 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] ) && $paramSettings[self
::PARAM_DEPRECATED
] ) {
394 $desc = "DEPRECATED! $desc";
397 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] ) && $paramSettings[self
::PARAM_REQUIRED
] ) {
398 $desc .= $paramPrefix . "This parameter is required";
401 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
402 if ( isset( $type ) ) {
403 $hintPipeSeparated = true;
404 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
406 $prompt = 'Values (separate with \'|\'): ';
408 $prompt = 'One value: ';
411 if ( is_array( $type ) ) {
414 foreach ( $type as $t ) {
416 $nothingPrompt = 'Can be empty, or ';
421 $desc .= $paramPrefix . $nothingPrompt . $prompt;
422 $choicesstring = implode( ', ', $choices );
423 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
424 $hintPipeSeparated = false;
428 // Special handling because namespaces are type-limited, yet they are not given
429 $desc .= $paramPrefix . $prompt;
430 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
431 100, $descWordwrap );
432 $hintPipeSeparated = false;
435 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
436 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
437 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
442 $s = $multi ?
's' : '';
443 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
444 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
445 if ( $hasMin ||
$hasMax ) {
447 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
448 } elseif ( !$hasMin ) {
449 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
451 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
454 $desc .= $paramPrefix . $intRangeStr;
461 if ( $hintPipeSeparated ) {
462 $desc .= $paramPrefix . "Separate values with '|'";
465 $isArray = is_array( $type );
467 ||
$isArray && count( $type ) > self
::LIMIT_SML1
) {
468 $desc .= $paramPrefix . "Maximum number of values " .
469 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
474 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
475 if ( !is_null( $default ) && $default !== false ) {
476 $desc .= $paramPrefix . "Default: $default";
479 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
489 * Returns the description string for this module
490 * @return mixed string or array of strings
492 protected function getDescription() {
497 * Returns usage examples for this module. Return false if no examples are available.
498 * @return bool|string|array
500 protected function getExamples() {
505 * Returns an array of allowed parameters (parameter name) => (default
506 * value) or (parameter name) => (array with PARAM_* constants as keys)
507 * Don't call this function directly: use getFinalParams() to allow
508 * hooks to modify parameters as needed.
511 protected function getAllowedParams() {
516 * Returns an array of parameter descriptions.
517 * Don't call this functon directly: use getFinalParamDescription() to
518 * allow hooks to modify descriptions as needed.
519 * @return array|bool False on no parameter descriptions
521 protected function getParamDescription() {
526 * Get final list of parameters, after hooks have had a chance to
527 * tweak it as needed.
529 * @return array|Bool False on no parameters
531 public function getFinalParams() {
532 $params = $this->getAllowedParams();
533 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
538 * Get final parameter descriptions, after hooks have had a chance to tweak it as
541 * @return array|bool False on no parameter descriptions
543 public function getFinalParamDescription() {
544 $desc = $this->getParamDescription();
545 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
550 * Returns possible properties in the result, grouped by the value of the prop parameter
553 * Properties that are shown always are in a group with empty string as a key.
554 * Properties that can be shown by several values of prop are included multiple times.
555 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
556 * those on the root object are under the key PROP_ROOT.
557 * The array can also contain a boolean under the key PROP_LIST,
558 * indicating whether the result is a list.
560 * Don't call this functon directly: use getFinalResultProperties() to
561 * allow hooks to modify descriptions as needed.
563 * @return array|bool False on no properties
565 protected function getResultProperties() {
570 * Get final possible result properties, after hooks have had a chance to tweak it as
575 public function getFinalResultProperties() {
576 $properties = $this->getResultProperties();
577 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
582 * Add token properties to the array used by getResultProperties,
583 * based on a token functions mapping.
585 protected static function addTokenProperties( &$props, $tokenFunctions ) {
586 foreach ( array_keys( $tokenFunctions ) as $token ) {
587 $props[''][$token . 'token'] = array(
588 ApiBase
::PROP_TYPE
=> 'string',
589 ApiBase
::PROP_NULLABLE
=> true
595 * Get final module description, after hooks have had a chance to tweak it as
598 * @return array|bool False on no parameters
600 public function getFinalDescription() {
601 $desc = $this->getDescription();
602 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
607 * This method mangles parameter name based on the prefix supplied to the constructor.
608 * Override this method to change parameter name during runtime
609 * @param $paramName string Parameter name
610 * @return string Prefixed parameter name
612 public function encodeParamName( $paramName ) {
613 return $this->mModulePrefix
. $paramName;
617 * Using getAllowedParams(), this function makes an array of the values
618 * provided by the user, with key being the name of the variable, and
619 * value - validated value from user or default. limits will not be
620 * parsed if $parseLimit is set to false; use this when the max
621 * limit is not definitive yet, e.g. when getting revisions.
622 * @param $parseLimit Boolean: true by default
625 public function extractRequestParams( $parseLimit = true ) {
626 // Cache parameters, for performance and to avoid bug 24564.
627 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
628 $params = $this->getFinalParams();
631 if ( $params ) { // getFinalParams() can return false
632 foreach ( $params as $paramName => $paramSettings ) {
633 $results[$paramName] = $this->getParameterFromSettings(
634 $paramName, $paramSettings, $parseLimit );
637 $this->mParamCache
[$parseLimit] = $results;
639 return $this->mParamCache
[$parseLimit];
643 * Get a value for the given parameter
644 * @param $paramName string Parameter name
645 * @param $parseLimit bool see extractRequestParams()
646 * @return mixed Parameter value
648 protected function getParameter( $paramName, $parseLimit = true ) {
649 $params = $this->getFinalParams();
650 $paramSettings = $params[$paramName];
651 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
655 * Die if none or more than one of a certain set of parameters is set and not false.
656 * @param $params array of parameter names
658 public function requireOnlyOneParameter( $params ) {
659 $required = func_get_args();
660 array_shift( $required );
661 $p = $this->getModulePrefix();
663 $intersection = array_intersect( array_keys( array_filter( $params,
664 array( $this, "parameterNotEmpty" ) ) ), $required );
666 if ( count( $intersection ) > 1 ) {
667 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
668 } elseif ( count( $intersection ) == 0 ) {
669 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
674 * Generates the possible errors requireOnlyOneParameter() can die with
676 * @param $params array
679 public function getRequireOnlyOneParameterErrorMessages( $params ) {
680 $p = $this->getModulePrefix();
681 $params = implode( ", {$p}", $params );
684 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
685 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
690 * Die if more than one of a certain set of parameters is set and not false.
692 * @param $params array
694 public function requireMaxOneParameter( $params ) {
695 $required = func_get_args();
696 array_shift( $required );
697 $p = $this->getModulePrefix();
699 $intersection = array_intersect( array_keys( array_filter( $params,
700 array( $this, "parameterNotEmpty" ) ) ), $required );
702 if ( count( $intersection ) > 1 ) {
703 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
708 * Generates the possible error requireMaxOneParameter() can die with
710 * @param $params array
713 public function getRequireMaxOneParameterErrorMessages( $params ) {
714 $p = $this->getModulePrefix();
715 $params = implode( ", {$p}", $params );
718 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
723 * @param $params array
724 * @param $load bool|string Whether load the object's state from the database:
725 * - false: don't load (if the pageid is given, it will still be loaded)
726 * - 'fromdb': load from a slave database
727 * - 'fromdbmaster': load from the master database
730 public function getTitleOrPageId( $params, $load = false ) {
731 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
734 if ( isset( $params['title'] ) ) {
735 $titleObj = Title
::newFromText( $params['title'] );
737 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
739 if ( !$titleObj->canExist() ) {
740 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
742 $pageObj = WikiPage
::factory( $titleObj );
743 if ( $load !== false ) {
744 $pageObj->loadPageData( $load );
746 } elseif ( isset( $params['pageid'] ) ) {
747 if ( $load === false ) {
750 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
752 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
762 public function getTitleOrPageIdErrorMessage() {
764 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
766 array( 'invalidtitle', 'title' ),
767 array( 'nosuchpageid', 'pageid' ),
773 * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set
775 * @param $x object Parameter to check is not null/false
778 private function parameterNotEmpty( $x ) {
779 return !is_null( $x ) && $x !== false;
783 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
787 public static function getValidNamespaces() {
788 wfDeprecated( __METHOD__
, '1.17' );
789 return MWNamespace
::getValidNamespaces();
793 * Return true if we're to watch the page, false if not, null if no change.
794 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
795 * @param $titleObj Title the page under consideration
796 * @param $userOption String The user option to consider when $watchlist=preferences.
797 * If not set will magically default to either watchdefault or watchcreations
800 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
802 $userWatching = $this->getUser()->isWatched( $titleObj );
804 switch ( $watchlist ) {
812 # If the user is already watching, don't bother checking
813 if ( $userWatching ) {
816 # If no user option was passed, use watchdefault or watchcreation
817 if ( is_null( $userOption ) ) {
818 $userOption = $titleObj->exists()
819 ?
'watchdefault' : 'watchcreations';
821 # Watch the article based on the user preference
822 return (bool)$this->getUser()->getOption( $userOption );
825 return $userWatching;
828 return $userWatching;
833 * Set a watch (or unwatch) based the based on a watchlist parameter.
834 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
835 * @param $titleObj Title the article's title to change
836 * @param $userOption String The user option to consider when $watch=preferences
838 protected function setWatch( $watch, $titleObj, $userOption = null ) {
839 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
840 if ( $value === null ) {
844 $user = $this->getUser();
846 WatchAction
::doWatch( $titleObj, $user );
848 WatchAction
::doUnwatch( $titleObj, $user );
853 * Using the settings determine the value for the given parameter
855 * @param $paramName String: parameter name
856 * @param $paramSettings array|mixed default value or an array of settings
857 * using PARAM_* constants.
858 * @param $parseLimit Boolean: parse limit?
859 * @return mixed Parameter value
861 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
862 // Some classes may decide to change parameter names
863 $encParamName = $this->encodeParamName( $paramName );
865 if ( !is_array( $paramSettings ) ) {
866 $default = $paramSettings;
868 $type = gettype( $paramSettings );
873 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
874 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
875 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
876 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
877 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
878 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
880 // When type is not given, and no choices, the type is the same as $default
881 if ( !isset( $type ) ) {
882 if ( isset( $default ) ) {
883 $type = gettype( $default );
885 $type = 'NULL'; // allow everything
890 if ( $type == 'boolean' ) {
891 if ( isset( $default ) && $default !== false ) {
892 // Having a default value of anything other than 'false' is not allowed
893 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
896 $value = $this->getMain()->getCheck( $encParamName );
898 $value = $this->getMain()->getVal( $encParamName, $default );
900 if ( isset( $value ) && $type == 'namespace' ) {
901 $type = MWNamespace
::getValidNamespaces();
905 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
906 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
909 // More validation only when choices were not given
910 // choices were validated in parseMultiValue()
911 if ( isset( $value ) ) {
912 if ( !is_array( $type ) ) {
914 case 'NULL': // nothing to do
917 if ( $required && $value === '' ) {
918 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
922 case 'integer': // Force everything using intval() and optionally validate limits
923 $min = isset ( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
924 $max = isset ( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
925 $enforceLimits = isset ( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
926 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
928 if ( is_array( $value ) ) {
929 $value = array_map( 'intval', $value );
930 if ( !is_null( $min ) ||
!is_null( $max ) ) {
931 foreach ( $value as &$v ) {
932 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
936 $value = intval( $value );
937 if ( !is_null( $min ) ||
!is_null( $max ) ) {
938 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
943 if ( !$parseLimit ) {
944 // Don't do any validation whatsoever
947 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
948 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
951 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
953 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
954 if ( $value == 'max' ) {
955 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
956 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
958 $value = intval( $value );
959 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
964 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
968 if ( is_array( $value ) ) {
969 foreach ( $value as $key => $val ) {
970 $value[$key] = $this->validateTimestamp( $val, $encParamName );
973 $value = $this->validateTimestamp( $value, $encParamName );
977 if ( !is_array( $value ) ) {
978 $value = array( $value );
981 foreach ( $value as $key => $val ) {
982 $title = Title
::makeTitleSafe( NS_USER
, $val );
983 if ( is_null( $title ) ) {
984 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
986 $value[$key] = $title->getText();
994 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
998 // Throw out duplicates if requested
999 if ( is_array( $value ) && !$dupes ) {
1000 $value = array_unique( $value );
1003 // Set a warning if a deprecated parameter has been passed
1004 if ( $deprecated && $value !== false ) {
1005 $this->setWarning( "The $encParamName parameter has been deprecated." );
1007 } elseif ( $required ) {
1008 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1015 * Return an array of values that were given in a 'a|b|c' notation,
1016 * after it optionally validates them against the list allowed values.
1018 * @param $valueName string The name of the parameter (for error
1020 * @param $value mixed The value being parsed
1021 * @param $allowMultiple bool Can $value contain more than one value
1023 * @param $allowedValues mixed An array of values to check against. If
1024 * null, all values are accepted.
1025 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1027 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1028 if ( trim( $value ) === '' && $allowMultiple ) {
1032 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1033 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1034 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
1035 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
1037 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1038 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1041 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1042 // Bug 33482 - Allow entries with | in them for non-multiple values
1043 if ( in_array( $value, $allowedValues ) ) {
1047 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
1048 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1051 if ( is_array( $allowedValues ) ) {
1052 // Check for unknown values
1053 $unknown = array_diff( $valuesList, $allowedValues );
1054 if ( count( $unknown ) ) {
1055 if ( $allowMultiple ) {
1056 $s = count( $unknown ) > 1 ?
's' : '';
1057 $vals = implode( ", ", $unknown );
1058 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1060 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1063 // Now throw them out
1064 $valuesList = array_intersect( $valuesList, $allowedValues );
1067 return $allowMultiple ?
$valuesList : $valuesList[0];
1071 * Validate the value against the minimum and user/bot maximum limits.
1072 * Prints usage info on failure.
1073 * @param $paramName string Parameter name
1074 * @param $value int Parameter value
1075 * @param $min int|null Minimum value
1076 * @param $max int|null Maximum value for users
1077 * @param $botMax int Maximum value for sysops/bots
1078 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1080 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1081 if ( !is_null( $min ) && $value < $min ) {
1083 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1084 $this->warnOrDie( $msg, $enforceLimits );
1088 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1089 if ( $this->getMain()->isInternalMode() ) {
1093 // Optimization: do not check user's bot status unless really needed -- skips db query
1094 // assumes $botMax >= $max
1095 if ( !is_null( $max ) && $value > $max ) {
1096 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1097 if ( $value > $botMax ) {
1098 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1099 $this->warnOrDie( $msg, $enforceLimits );
1103 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1104 $this->warnOrDie( $msg, $enforceLimits );
1111 * @param $value string
1112 * @param $paramName string
1115 function validateTimestamp( $value, $paramName ) {
1116 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1117 if ( $unixTimestamp === false ) {
1118 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
1120 return wfTimestamp( TS_MW
, $unixTimestamp );
1124 * Adds a warning to the output, else dies
1126 * @param $msg String Message to show as a warning, or error message if dying
1127 * @param $enforceLimits Boolean Whether this is an enforce (die)
1129 private function warnOrDie( $msg, $enforceLimits = false ) {
1130 if ( $enforceLimits ) {
1131 $this->dieUsage( $msg, 'integeroutofrange' );
1133 $this->setWarning( $msg );
1138 * Truncate an array to a certain length.
1139 * @param $arr array Array to truncate
1140 * @param $limit int Maximum length
1141 * @return bool True if the array was truncated, false otherwise
1143 public static function truncateArray( &$arr, $limit ) {
1145 while ( count( $arr ) > $limit ) {
1153 * Throw a UsageException, which will (if uncaught) call the main module's
1154 * error handler and die with an error message.
1156 * @param $description string One-line human-readable description of the
1157 * error condition, e.g., "The API requires a valid action parameter"
1158 * @param $errorCode string Brief, arbitrary, stable string to allow easy
1159 * automated identification of the error, e.g., 'unknown_action'
1160 * @param $httpRespCode int HTTP response code
1161 * @param $extradata array Data to add to the "<error>" element; array in ApiResult format
1162 * @throws UsageException
1164 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1165 Profiler
::instance()->close();
1166 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1170 * Array that maps message keys to error messages. $1 and friends are replaced.
1172 public static $messageMap = array(
1173 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1174 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1175 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1177 // Messages from Title::getUserPermissionsErrors()
1178 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1179 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1180 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1181 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1182 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1183 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1184 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1185 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1186 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1187 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1188 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1189 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1190 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1191 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1192 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1193 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
1194 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1195 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1197 // Miscellaneous interface messages
1198 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1199 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1200 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1201 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1202 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1203 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1204 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1205 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1206 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1207 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1208 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1209 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1210 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1211 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1212 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1213 // 'badarticleerror' => shouldn't happen
1214 // 'badtitletext' => shouldn't happen
1215 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1216 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1217 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1218 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1219 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1220 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1221 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP invidually, but you can unblock the range as a whole." ),
1222 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1223 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed e-mail address, or you are not allowed to send e-mail to other users, so you cannot send e-mail" ),
1224 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1225 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1226 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1227 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
1228 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1229 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users" ),
1230 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1231 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1232 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1233 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1234 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1235 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1236 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1237 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1238 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1239 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1240 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1242 // API-specific messages
1243 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1244 '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" ),
1245 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1246 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1247 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1248 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1249 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1250 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1251 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1252 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1253 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1254 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1255 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1256 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1257 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1258 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
1259 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1260 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1261 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1262 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1263 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1264 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1265 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1266 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1267 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1268 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1269 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1270 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1271 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1272 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1273 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1274 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1275 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1276 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1277 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1278 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1279 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1280 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1281 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1282 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1283 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1284 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1285 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1286 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1287 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1288 '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.' ),
1289 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1291 // ApiEditPage messages
1292 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1293 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1294 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1295 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1296 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1297 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1298 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1299 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1300 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1301 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1302 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1303 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1304 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1305 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1307 // Messages from WikiPage::doEit()
1308 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1309 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1310 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1311 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1314 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1315 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1316 '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' ),
1317 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1318 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1320 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1321 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1322 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1323 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1325 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1329 * Helper function for readonly errors
1331 public function dieReadOnly() {
1332 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1333 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1334 array( 'readonlyreason' => wfReadOnlyReason() ) );
1338 * Output the error message related to a certain array
1339 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1341 public function dieUsageMsg( $error ) {
1342 # most of the time we send a 1 element, so we might as well send it as
1343 # a string and make this an array here.
1344 if( is_string( $error ) ) {
1345 $error = array( $error );
1347 $parsed = $this->parseMsg( $error );
1348 $this->dieUsage( $parsed['info'], $parsed['code'] );
1352 * Will only set a warning instead of failing if the global $wgDebugAPI
1353 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1354 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1357 public function dieUsageMsgOrDebug( $error ) {
1359 if( $wgDebugAPI !== true ) {
1360 $this->dieUsageMsg( $error );
1362 if( is_string( $error ) ) {
1363 $error = array( $error );
1365 $parsed = $this->parseMsg( $error );
1366 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1367 . ' - ' . $parsed['info'] );
1372 * Return the error message related to a certain array
1373 * @param $error array Element of a getUserPermissionsErrors()-style array
1374 * @return array('code' => code, 'info' => info)
1376 public function parseMsg( $error ) {
1377 $error = (array)$error; // It seems strings sometimes make their way in here
1378 $key = array_shift( $error );
1380 // Check whether the error array was nested
1381 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1382 if( is_array( $key ) ) {
1384 $key = array_shift( $error );
1387 if ( isset( self
::$messageMap[$key] ) ) {
1389 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1390 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1394 // If the key isn't present, throw an "unknown error"
1395 return $this->parseMsg( array( 'unknownerror', $key ) );
1399 * Internal code errors should be reported with this method
1400 * @param $method string Method or function name
1401 * @param $message string Error message
1403 protected static function dieDebug( $method, $message ) {
1404 wfDebugDieBacktrace( "Internal error in $method: $message" );
1408 * Indicates if this module needs maxlag to be checked
1411 public function shouldCheckMaxlag() {
1416 * Indicates whether this module requires read rights
1419 public function isReadMode() {
1423 * Indicates whether this module requires write mode
1426 public function isWriteMode() {
1431 * Indicates whether this module must be called with a POST request
1434 public function mustBePosted() {
1439 * Returns whether this module requires a token to execute
1440 * It is used to show possible errors in action=paraminfo
1444 public function needsToken() {
1449 * Returns the token salt if there is one,
1450 * '' if the module doesn't require a salt,
1451 * else false if the module doesn't need a token
1452 * You have also to override needsToken()
1453 * Value is passed to User::getEditToken
1454 * @return bool|string|array
1456 public function getTokenSalt() {
1461 * Gets the user for whom to get the watchlist
1463 * @param $params array
1466 public function getWatchlistUser( $params ) {
1467 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1468 $user = User
::newFromName( $params['owner'], false );
1469 if ( !($user && $user->getId()) ) {
1470 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1472 $token = $user->getOption( 'watchlisttoken' );
1473 if ( $token == '' ||
$token != $params['token'] ) {
1474 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1477 if ( !$this->getUser()->isLoggedIn() ) {
1478 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1480 $user = $this->getUser();
1486 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1488 public function getHelpUrls() {
1493 * Returns a list of all possible errors returned by the module
1494 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1496 public function getPossibleErrors() {
1499 $params = $this->getFinalParams();
1501 foreach ( $params as $paramName => $paramSettings ) {
1502 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) ) {
1503 $ret[] = array( 'missingparam', $paramName );
1508 if ( $this->mustBePosted() ) {
1509 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1512 if ( $this->isReadMode() ) {
1513 $ret[] = array( 'readrequired' );
1516 if ( $this->isWriteMode() ) {
1517 $ret[] = array( 'writerequired' );
1518 $ret[] = array( 'writedisabled' );
1521 if ( $this->needsToken() ) {
1522 $ret[] = array( 'missingparam', 'token' );
1523 $ret[] = array( 'sessionfailure' );
1530 * Parses a list of errors into a standardised format
1531 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1532 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1534 public function parseErrors( $errors ) {
1537 foreach ( $errors as $row ) {
1538 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1541 $ret[] = $this->parseMsg( $row );
1548 * Profiling: total module execution time
1550 private $mTimeIn = 0, $mModuleTime = 0;
1553 * Start module profiling
1555 public function profileIn() {
1556 if ( $this->mTimeIn
!== 0 ) {
1557 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1559 $this->mTimeIn
= microtime( true );
1560 wfProfileIn( $this->getModuleProfileName() );
1564 * End module profiling
1566 public function profileOut() {
1567 if ( $this->mTimeIn
=== 0 ) {
1568 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1570 if ( $this->mDBTimeIn
!== 0 ) {
1571 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1574 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1576 wfProfileOut( $this->getModuleProfileName() );
1580 * When modules crash, sometimes it is needed to do a profileOut() regardless
1581 * of the profiling state the module was in. This method does such cleanup.
1583 public function safeProfileOut() {
1584 if ( $this->mTimeIn
!== 0 ) {
1585 if ( $this->mDBTimeIn
!== 0 ) {
1586 $this->profileDBOut();
1588 $this->profileOut();
1593 * Total time the module was executed
1596 public function getProfileTime() {
1597 if ( $this->mTimeIn
!== 0 ) {
1598 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1600 return $this->mModuleTime
;
1604 * Profiling: database execution time
1606 private $mDBTimeIn = 0, $mDBTime = 0;
1609 * Start module profiling
1611 public function profileDBIn() {
1612 if ( $this->mTimeIn
=== 0 ) {
1613 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1615 if ( $this->mDBTimeIn
!== 0 ) {
1616 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1618 $this->mDBTimeIn
= microtime( true );
1619 wfProfileIn( $this->getModuleProfileName( true ) );
1623 * End database profiling
1625 public function profileDBOut() {
1626 if ( $this->mTimeIn
=== 0 ) {
1627 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1629 if ( $this->mDBTimeIn
=== 0 ) {
1630 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1633 $time = microtime( true ) - $this->mDBTimeIn
;
1634 $this->mDBTimeIn
= 0;
1636 $this->mDBTime +
= $time;
1637 $this->getMain()->mDBTime +
= $time;
1638 wfProfileOut( $this->getModuleProfileName( true ) );
1642 * Total time the module used the database
1645 public function getProfileDBTime() {
1646 if ( $this->mDBTimeIn
!== 0 ) {
1647 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1649 return $this->mDBTime
;
1653 * @return DatabaseBase
1655 protected function getDB() {
1656 return wfGetDB( DB_SLAVE
, 'api' );
1660 * Debugging function that prints a value and an optional backtrace
1661 * @param $value mixed Value to print
1662 * @param $name string Description of the printed value
1663 * @param $backtrace bool If true, print a backtrace
1665 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1666 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1667 var_export( $value );
1669 print "\n" . wfBacktrace();