5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT
= 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST
= 'LIST';
74 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE
= 1;
78 const LIMIT_BIG1
= 500; // Fast query, std user limit
79 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1
= 50; // Slow query, std user limit
81 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
88 const GET_VALUES_FOR_HELP
= 1;
90 private $mMainModule, $mModuleName, $mModulePrefix;
91 private $mSlaveDB = null;
92 private $mParamCache = array();
96 * @param $mainModule ApiMain object
97 * @param string $moduleName Name of this module
98 * @param string $modulePrefix Prefix to use for parameter names
100 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
101 $this->mMainModule
= $mainModule;
102 $this->mModuleName
= $moduleName;
103 $this->mModulePrefix
= $modulePrefix;
105 if ( !$this->isMain() ) {
106 $this->setContext( $mainModule->getContext() );
110 /*****************************************************************************
112 *****************************************************************************/
115 * Evaluates the parameters, performs the requested query, and sets up
116 * the result. Concrete implementations of ApiBase must override this
117 * method to provide whatever functionality their module offers.
118 * Implementations must not produce any output on their own and are not
119 * expected to handle any errors.
121 * The execute() method will be invoked directly by ApiMain immediately
122 * before the result of the module is output. Aside from the
123 * constructor, implementations should assume that no other methods
124 * will be called externally on the module before the result is
127 * The result data should be stored in the ApiResult object available
128 * through getResult().
130 abstract public function execute();
133 * Returns a string that identifies the version of the extending class.
134 * Typically includes the class name, the svn revision, timestamp, and
135 * last author. Usually done with SVN's Id keyword
137 * @deprecated since 1.21, version string is no longer supported
139 public function getVersion() {
140 wfDeprecated( __METHOD__
, '1.21' );
146 * Get the name of the module being executed by this instance
149 public function getModuleName() {
150 return $this->mModuleName
;
154 * Get the module manager, or null if this module has no sub-modules
156 * @return ApiModuleManager
158 public function getModuleManager() {
163 * Get parameter prefix (usually two letters or an empty string).
166 public function getModulePrefix() {
167 return $this->mModulePrefix
;
171 * Get the name of the module as shown in the profiler log
173 * @param $db DatabaseBase|bool
177 public function getModuleProfileName( $db = false ) {
179 return 'API:' . $this->mModuleName
. '-DB';
182 return 'API:' . $this->mModuleName
;
186 * Get the main module
187 * @return ApiMain object
189 public function getMain() {
190 return $this->mMainModule
;
194 * Returns true if this module is the main module ($this === $this->mMainModule),
198 public function isMain() {
199 return $this === $this->mMainModule
;
203 * Get the result object
206 public function getResult() {
207 // Main module has getResult() method overridden
208 // Safety - avoid infinite loop:
209 if ( $this->isMain() ) {
210 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
213 return $this->getMain()->getResult();
217 * Get the result data array (read-only)
220 public function getResultData() {
221 return $this->getResult()->getData();
225 * Create a new RequestContext object to use e.g. for calls to other parts
227 * The object will have the WebRequest and the User object set to the ones
228 * used in this instance.
230 * @deprecated since 1.19 use getContext to get the current context
231 * @return DerivativeContext
233 public function createContext() {
234 wfDeprecated( __METHOD__
, '1.19' );
236 return new DerivativeContext( $this->getContext() );
240 * Set warning section for this module. Users should monitor this
241 * section to notice any changes in API. Multiple calls to this
242 * function will result in the warning messages being separated by
244 * @param string $warning Warning message
246 public function setWarning( $warning ) {
247 $result = $this->getResult();
248 $data = $result->getData();
249 $moduleName = $this->getModuleName();
250 if ( isset( $data['warnings'][$moduleName] ) ) {
251 // Don't add duplicate warnings
252 $oldWarning = $data['warnings'][$moduleName]['*'];
253 $warnPos = strpos( $oldWarning, $warning );
254 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
255 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
256 // Check if $warning is followed by "\n" or the end of the $oldWarning
257 $warnPos +
= strlen( $warning );
258 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
262 // If there is a warning already, append it to the existing one
263 $warning = "$oldWarning\n$warning";
266 ApiResult
::setContent( $msg, $warning );
267 $result->disableSizeCheck();
268 $result->addValue( 'warnings', $moduleName,
269 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
270 $result->enableSizeCheck();
274 * If the module may only be used with a certain format module,
275 * it should override this method to return an instance of that formatter.
276 * A value of null means the default format will be used.
277 * @return mixed instance of a derived class of ApiFormatBase, or null
279 public function getCustomPrinter() {
284 * Generates help message for this module, or false if there is no description
285 * @return mixed string or false
287 public function makeHelpMsg() {
288 static $lnPrfx = "\n ";
290 $msg = $this->getFinalDescription();
292 if ( $msg !== false ) {
294 if ( !is_array( $msg ) ) {
299 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
301 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
303 if ( $this->isReadMode() ) {
304 $msg .= "\nThis module requires read rights";
306 if ( $this->isWriteMode() ) {
307 $msg .= "\nThis module requires write rights";
309 if ( $this->mustBePosted() ) {
310 $msg .= "\nThis module only accepts POST requests";
312 if ( $this->isReadMode() ||
$this->isWriteMode() ||
313 $this->mustBePosted()
319 $paramsMsg = $this->makeHelpMsgParameters();
320 if ( $paramsMsg !== false ) {
321 $msg .= "Parameters:\n$paramsMsg";
324 $examples = $this->getExamples();
326 if ( !is_array( $examples ) ) {
331 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
332 foreach ( $examples as $k => $v ) {
333 if ( is_numeric( $k ) ) {
336 if ( is_array( $v ) ) {
337 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
342 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
352 * @param $item string
355 private function indentExampleText( $item ) {
360 * @param string $prefix Text to split output items
361 * @param string $title What is being output
362 * @param $input string|array
365 protected function makeHelpArrayToString( $prefix, $title, $input ) {
366 if ( $input === false ) {
369 if ( !is_array( $input ) ) {
370 $input = array( $input );
373 if ( count( $input ) > 0 ) {
375 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
379 $msg .= implode( $prefix, $input ) . "\n";
388 * Generates the parameter descriptions for this module, to be displayed in the
390 * @return string or false
392 public function makeHelpMsgParameters() {
393 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
396 $paramsDescription = $this->getFinalParamDescription();
398 $paramPrefix = "\n" . str_repeat( ' ', 24 );
399 $descWordwrap = "\n" . str_repeat( ' ', 28 );
400 foreach ( $params as $paramName => $paramSettings ) {
401 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
402 if ( is_array( $desc ) ) {
403 $desc = implode( $paramPrefix, $desc );
407 if ( !is_array( $paramSettings ) ) {
408 $paramSettings = array(
409 self
::PARAM_DFLT
=> $paramSettings,
413 //handle missing type
414 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
415 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
416 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
418 if ( is_bool( $dflt ) ) {
419 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
420 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
421 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
422 } elseif ( is_int( $dflt ) ) {
423 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
427 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
428 && $paramSettings[self
::PARAM_DEPRECATED
]
430 $desc = "DEPRECATED! $desc";
433 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
434 && $paramSettings[self
::PARAM_REQUIRED
]
436 $desc .= $paramPrefix . "This parameter is required";
439 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
440 ?
$paramSettings[self
::PARAM_TYPE
]
442 if ( isset( $type ) ) {
443 $hintPipeSeparated = true;
444 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
445 ?
$paramSettings[self
::PARAM_ISMULTI
]
448 $prompt = 'Values (separate with \'|\'): ';
450 $prompt = 'One value: ';
453 if ( is_array( $type ) ) {
456 foreach ( $type as $t ) {
458 $nothingPrompt = 'Can be empty, or ';
463 $desc .= $paramPrefix . $nothingPrompt . $prompt;
464 $choicesstring = implode( ', ', $choices );
465 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
466 $hintPipeSeparated = false;
470 // Special handling because namespaces are
471 // type-limited, yet they are not given
472 $desc .= $paramPrefix . $prompt;
473 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
474 100, $descWordwrap );
475 $hintPipeSeparated = false;
478 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
479 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
480 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
485 $s = $multi ?
's' : '';
486 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
487 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
488 if ( $hasMin ||
$hasMax ) {
490 $intRangeStr = "The value$s must be no less than " .
491 "{$paramSettings[self::PARAM_MIN]}";
492 } elseif ( !$hasMin ) {
493 $intRangeStr = "The value$s must be no more than " .
494 "{$paramSettings[self::PARAM_MAX]}";
496 $intRangeStr = "The value$s must be between " .
497 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
500 $desc .= $paramPrefix . $intRangeStr;
504 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
510 if ( $hintPipeSeparated ) {
511 $desc .= $paramPrefix . "Separate values with '|'";
514 $isArray = is_array( $type );
516 ||
$isArray && count( $type ) > self
::LIMIT_SML1
518 $desc .= $paramPrefix . "Maximum number of values " .
519 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
524 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
525 if ( !is_null( $default ) && $default !== false ) {
526 $desc .= $paramPrefix . "Default: $default";
529 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
539 * Returns the description string for this module
540 * @return mixed string or array of strings
542 protected function getDescription() {
547 * Returns usage examples for this module. Return false if no examples are available.
548 * @return bool|string|array
550 protected function getExamples() {
555 * Returns an array of allowed parameters (parameter name) => (default
556 * value) or (parameter name) => (array with PARAM_* constants as keys)
557 * Don't call this function directly: use getFinalParams() to allow
558 * hooks to modify parameters as needed.
560 * Some derived classes may choose to handle an integer $flags parameter
561 * in the overriding methods. Callers of this method can pass zero or
562 * more OR-ed flags like GET_VALUES_FOR_HELP.
566 protected function getAllowedParams( /* $flags = 0 */ ) {
567 // int $flags is not declared because it causes "Strict standards"
568 // warning. Most derived classes do not implement it.
573 * Returns an array of parameter descriptions.
574 * Don't call this function directly: use getFinalParamDescription() to
575 * allow hooks to modify descriptions as needed.
576 * @return array|bool False on no parameter descriptions
578 protected function getParamDescription() {
583 * Get final list of parameters, after hooks have had a chance to
584 * tweak it as needed.
586 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
587 * @return array|Bool False on no parameters
588 * @since 1.21 $flags param added
590 public function getFinalParams( $flags = 0 ) {
591 $params = $this->getAllowedParams( $flags );
592 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
598 * Get final parameter descriptions, after hooks have had a chance to tweak it as
601 * @return array|bool False on no parameter descriptions
603 public function getFinalParamDescription() {
604 $desc = $this->getParamDescription();
605 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
611 * Returns possible properties in the result, grouped by the value of the prop parameter
614 * Properties that are shown always are in a group with empty string as a key.
615 * Properties that can be shown by several values of prop are included multiple times.
616 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
617 * those on the root object are under the key PROP_ROOT.
618 * The array can also contain a boolean under the key PROP_LIST,
619 * indicating whether the result is a list.
621 * Don't call this function directly: use getFinalResultProperties() to
622 * allow hooks to modify descriptions as needed.
624 * @return array|bool False on no properties
626 protected function getResultProperties() {
631 * Get final possible result properties, after hooks have had a chance to tweak it as
636 public function getFinalResultProperties() {
637 $properties = $this->getResultProperties();
638 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
644 * Add token properties to the array used by getResultProperties,
645 * based on a token functions mapping.
647 protected static function addTokenProperties( &$props, $tokenFunctions ) {
648 foreach ( array_keys( $tokenFunctions ) as $token ) {
649 $props[''][$token . 'token'] = array(
650 ApiBase
::PROP_TYPE
=> 'string',
651 ApiBase
::PROP_NULLABLE
=> true
657 * Get final module description, after hooks have had a chance to tweak it as
660 * @return array|bool False on no parameters
662 public function getFinalDescription() {
663 $desc = $this->getDescription();
664 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
670 * This method mangles parameter name based on the prefix supplied to the constructor.
671 * Override this method to change parameter name during runtime
672 * @param string $paramName Parameter name
673 * @return string Prefixed parameter name
675 public function encodeParamName( $paramName ) {
676 return $this->mModulePrefix
. $paramName;
680 * Using getAllowedParams(), this function makes an array of the values
681 * provided by the user, with key being the name of the variable, and
682 * value - validated value from user or default. limits will not be
683 * parsed if $parseLimit is set to false; use this when the max
684 * limit is not definitive yet, e.g. when getting revisions.
685 * @param $parseLimit Boolean: true by default
688 public function extractRequestParams( $parseLimit = true ) {
689 // Cache parameters, for performance and to avoid bug 24564.
690 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
691 $params = $this->getFinalParams();
694 if ( $params ) { // getFinalParams() can return false
695 foreach ( $params as $paramName => $paramSettings ) {
696 $results[$paramName] = $this->getParameterFromSettings(
697 $paramName, $paramSettings, $parseLimit );
700 $this->mParamCache
[$parseLimit] = $results;
703 return $this->mParamCache
[$parseLimit];
707 * Get a value for the given parameter
708 * @param string $paramName Parameter name
709 * @param bool $parseLimit see extractRequestParams()
710 * @return mixed Parameter value
712 protected function getParameter( $paramName, $parseLimit = true ) {
713 $params = $this->getFinalParams();
714 $paramSettings = $params[$paramName];
716 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
720 * Die if none or more than one of a certain set of parameters is set and not false.
721 * @param array $params of parameter names
723 public function requireOnlyOneParameter( $params ) {
724 $required = func_get_args();
725 array_shift( $required );
726 $p = $this->getModulePrefix();
728 $intersection = array_intersect( array_keys( array_filter( $params,
729 array( $this, "parameterNotEmpty" ) ) ), $required );
731 if ( count( $intersection ) > 1 ) {
733 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
735 } elseif ( count( $intersection ) == 0 ) {
737 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
744 * Generates the possible errors requireOnlyOneParameter() can die with
746 * @param $params array
749 public function getRequireOnlyOneParameterErrorMessages( $params ) {
750 $p = $this->getModulePrefix();
751 $params = implode( ", {$p}", $params );
755 'code' => "{$p}missingparam",
756 'info' => "One of the parameters {$p}{$params} is required"
759 'code' => "{$p}invalidparammix",
760 'info' => "The parameters {$p}{$params} can not be used together"
766 * Die if more than one of a certain set of parameters is set and not false.
768 * @param $params array
770 public function requireMaxOneParameter( $params ) {
771 $required = func_get_args();
772 array_shift( $required );
773 $p = $this->getModulePrefix();
775 $intersection = array_intersect( array_keys( array_filter( $params,
776 array( $this, "parameterNotEmpty" ) ) ), $required );
778 if ( count( $intersection ) > 1 ) {
780 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
787 * Generates the possible error requireMaxOneParameter() can die with
789 * @param $params array
792 public function getRequireMaxOneParameterErrorMessages( $params ) {
793 $p = $this->getModulePrefix();
794 $params = implode( ", {$p}", $params );
798 'code' => "{$p}invalidparammix",
799 'info' => "The parameters {$p}{$params} can not be used together"
805 * Die if none of a certain set of parameters is set and not false.
808 * @param array $params User provided set of parameters
809 * @param string ... List of parameter names to check
811 public function requireAtLeastOneParameter( $params ) {
812 $required = func_get_args();
813 array_shift( $required );
814 $p = $this->getModulePrefix();
816 $intersection = array_intersect(
817 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
821 if ( count( $intersection ) == 0 ) {
822 $this->dieUsage( "At least one of the parameters {$p}" .
823 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
828 * Generates the possible errors requireAtLeastOneParameter() can die with
831 * @param $params array Array of parameter key names
834 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
835 $p = $this->getModulePrefix();
836 $params = implode( ", {$p}", $params );
840 'code' => "{$p}missingparam",
841 'info' => "At least one of the parameters {$p}{$params} is required",
847 * @param $params array
848 * @param bool|string $load Whether load the object's state from the database:
849 * - false: don't load (if the pageid is given, it will still be loaded)
850 * - 'fromdb': load from a slave database
851 * - 'fromdbmaster': load from the master database
854 public function getTitleOrPageId( $params, $load = false ) {
855 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
858 if ( isset( $params['title'] ) ) {
859 $titleObj = Title
::newFromText( $params['title'] );
860 if ( !$titleObj ||
$titleObj->isExternal() ) {
861 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
863 if ( !$titleObj->canExist() ) {
864 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
866 $pageObj = WikiPage
::factory( $titleObj );
867 if ( $load !== false ) {
868 $pageObj->loadPageData( $load );
870 } elseif ( isset( $params['pageid'] ) ) {
871 if ( $load === false ) {
874 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
876 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
886 public function getTitleOrPageIdErrorMessage() {
888 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
890 array( 'invalidtitle', 'title' ),
891 array( 'nosuchpageid', 'pageid' ),
897 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
899 * @param $x object Parameter to check is not null/false
902 private function parameterNotEmpty( $x ) {
903 return !is_null( $x ) && $x !== false;
907 * Return true if we're to watch the page, false if not, null if no change.
908 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
909 * @param $titleObj Title the page under consideration
910 * @param string $userOption The user option to consider when $watchlist=preferences.
911 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
914 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
916 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
918 switch ( $watchlist ) {
926 # If the user is already watching, don't bother checking
927 if ( $userWatching ) {
930 # If no user option was passed, use watchdefault and watchcreations
931 if ( is_null( $userOption ) ) {
932 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
933 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
936 # Watch the article based on the user preference
937 return $this->getUser()->getBoolOption( $userOption );
940 return $userWatching;
943 return $userWatching;
948 * Set a watch (or unwatch) based the based on a watchlist parameter.
949 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
950 * @param $titleObj Title the article's title to change
951 * @param string $userOption The user option to consider when $watch=preferences
953 protected function setWatch( $watch, $titleObj, $userOption = null ) {
954 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
955 if ( $value === null ) {
959 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
963 * Using the settings determine the value for the given parameter
965 * @param string $paramName parameter name
966 * @param array|mixed $paramSettings default value or an array of settings
967 * using PARAM_* constants.
968 * @param $parseLimit Boolean: parse limit?
969 * @return mixed Parameter value
971 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
972 // Some classes may decide to change parameter names
973 $encParamName = $this->encodeParamName( $paramName );
975 if ( !is_array( $paramSettings ) ) {
976 $default = $paramSettings;
978 $type = gettype( $paramSettings );
983 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
984 ?
$paramSettings[self
::PARAM_DFLT
]
986 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
987 ?
$paramSettings[self
::PARAM_ISMULTI
]
989 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
990 ?
$paramSettings[self
::PARAM_TYPE
]
992 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
993 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
995 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
996 ?
$paramSettings[self
::PARAM_DEPRECATED
]
998 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
999 ?
$paramSettings[self
::PARAM_REQUIRED
]
1002 // When type is not given, and no choices, the type is the same as $default
1003 if ( !isset( $type ) ) {
1004 if ( isset( $default ) ) {
1005 $type = gettype( $default );
1007 $type = 'NULL'; // allow everything
1012 if ( $type == 'boolean' ) {
1013 if ( isset( $default ) && $default !== false ) {
1014 // Having a default value of anything other than 'false' is not allowed
1017 "Boolean param $encParamName's default is set to '$default'. " .
1018 "Boolean parameters must default to false."
1022 $value = $this->getMain()->getCheck( $encParamName );
1023 } elseif ( $type == 'upload' ) {
1024 if ( isset( $default ) ) {
1025 // Having a default value is not allowed
1028 "File upload param $encParamName's default is set to " .
1029 "'$default'. File upload parameters may not have a default." );
1032 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1034 $value = $this->getMain()->getUpload( $encParamName );
1035 if ( !$value->exists() ) {
1036 // This will get the value without trying to normalize it
1037 // (because trying to normalize a large binary file
1038 // accidentally uploaded as a field fails spectacularly)
1039 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1040 if ( $value !== null ) {
1042 "File upload param $encParamName is not a file upload; " .
1043 "be sure to use multipart/form-data for your POST and include " .
1044 "a filename in the Content-Disposition header.",
1045 "badupload_{$encParamName}"
1050 $value = $this->getMain()->getVal( $encParamName, $default );
1052 if ( isset( $value ) && $type == 'namespace' ) {
1053 $type = MWNamespace
::getValidNamespaces();
1057 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1058 $value = $this->parseMultiValue(
1062 is_array( $type ) ?
$type : null
1066 // More validation only when choices were not given
1067 // choices were validated in parseMultiValue()
1068 if ( isset( $value ) ) {
1069 if ( !is_array( $type ) ) {
1071 case 'NULL': // nothing to do
1074 if ( $required && $value === '' ) {
1075 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1078 case 'integer': // Force everything using intval() and optionally validate limits
1079 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1080 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1081 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1082 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1084 if ( is_array( $value ) ) {
1085 $value = array_map( 'intval', $value );
1086 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1087 foreach ( $value as &$v ) {
1088 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1092 $value = intval( $value );
1093 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1094 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1099 if ( !$parseLimit ) {
1100 // Don't do any validation whatsoever
1103 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1104 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1108 "MAX1 or MAX2 are not defined for the limit $encParamName"
1112 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1114 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1115 if ( $value == 'max' ) {
1116 $value = $this->getMain()->canApiHighLimits()
1117 ?
$paramSettings[self
::PARAM_MAX2
]
1118 : $paramSettings[self
::PARAM_MAX
];
1119 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1121 $value = intval( $value );
1122 $this->validateLimit(
1126 $paramSettings[self
::PARAM_MAX
],
1127 $paramSettings[self
::PARAM_MAX2
]
1133 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1137 if ( is_array( $value ) ) {
1138 foreach ( $value as $key => $val ) {
1139 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1142 $value = $this->validateTimestamp( $value, $encParamName );
1146 if ( is_array( $value ) ) {
1147 foreach ( $value as $key => $val ) {
1148 $value[$key] = $this->validateUser( $val, $encParamName );
1151 $value = $this->validateUser( $value, $encParamName );
1154 case 'upload': // nothing to do
1157 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1161 // Throw out duplicates if requested
1162 if ( !$dupes && is_array( $value ) ) {
1163 $value = array_unique( $value );
1166 // Set a warning if a deprecated parameter has been passed
1167 if ( $deprecated && $value !== false ) {
1168 $this->setWarning( "The $encParamName parameter has been deprecated." );
1170 } elseif ( $required ) {
1171 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1178 * Return an array of values that were given in a 'a|b|c' notation,
1179 * after it optionally validates them against the list allowed values.
1181 * @param string $valueName The name of the parameter (for error
1183 * @param $value mixed The value being parsed
1184 * @param bool $allowMultiple Can $value contain more than one value
1186 * @param $allowedValues mixed An array of values to check against. If
1187 * null, all values are accepted.
1188 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1190 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1191 if ( trim( $value ) === '' && $allowMultiple ) {
1195 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1196 // because it unstubs $wgUser
1197 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1198 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1202 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1203 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1204 "the limit is $sizeLimit" );
1207 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1208 // Bug 33482 - Allow entries with | in them for non-multiple values
1209 if ( in_array( $value, $allowedValues, true ) ) {
1213 $possibleValues = is_array( $allowedValues )
1214 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1217 "Only one $possibleValues is allowed for parameter '$valueName'",
1218 "multival_$valueName"
1222 if ( is_array( $allowedValues ) ) {
1223 // Check for unknown values
1224 $unknown = array_diff( $valuesList, $allowedValues );
1225 if ( count( $unknown ) ) {
1226 if ( $allowMultiple ) {
1227 $s = count( $unknown ) > 1 ?
's' : '';
1228 $vals = implode( ", ", $unknown );
1229 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1232 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1233 "unknown_$valueName"
1237 // Now throw them out
1238 $valuesList = array_intersect( $valuesList, $allowedValues );
1241 return $allowMultiple ?
$valuesList : $valuesList[0];
1245 * Validate the value against the minimum and user/bot maximum limits.
1246 * Prints usage info on failure.
1247 * @param string $paramName Parameter name
1248 * @param int $value Parameter value
1249 * @param int|null $min Minimum value
1250 * @param int|null $max Maximum value for users
1251 * @param int $botMax Maximum value for sysops/bots
1252 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1254 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1255 if ( !is_null( $min ) && $value < $min ) {
1257 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1258 $this->warnOrDie( $msg, $enforceLimits );
1262 // Minimum is always validated, whereas maximum is checked only if not
1263 // running in internal call mode
1264 if ( $this->getMain()->isInternalMode() ) {
1268 // Optimization: do not check user's bot status unless really needed -- skips db query
1269 // assumes $botMax >= $max
1270 if ( !is_null( $max ) && $value > $max ) {
1271 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1272 if ( $value > $botMax ) {
1273 $msg = $this->encodeParamName( $paramName ) .
1274 " may not be over $botMax (set to $value) for bots or sysops";
1275 $this->warnOrDie( $msg, $enforceLimits );
1279 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1280 $this->warnOrDie( $msg, $enforceLimits );
1287 * Validate and normalize of parameters of type 'timestamp'
1288 * @param string $value Parameter value
1289 * @param string $encParamName Parameter name
1290 * @return string Validated and normalized parameter
1292 function validateTimestamp( $value, $encParamName ) {
1293 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1294 if ( $unixTimestamp === false ) {
1296 "Invalid value '$value' for timestamp parameter $encParamName",
1297 "badtimestamp_{$encParamName}"
1301 return wfTimestamp( TS_MW
, $unixTimestamp );
1305 * Validate and normalize of parameters of type 'user'
1306 * @param string $value Parameter value
1307 * @param string $encParamName Parameter name
1308 * @return string Validated and normalized parameter
1310 private function validateUser( $value, $encParamName ) {
1311 $title = Title
::makeTitleSafe( NS_USER
, $value );
1312 if ( $title === null ) {
1314 "Invalid value '$value' for user parameter $encParamName",
1315 "baduser_{$encParamName}"
1319 return $title->getText();
1323 * Adds a warning to the output, else dies
1325 * @param $msg String Message to show as a warning, or error message if dying
1326 * @param $enforceLimits Boolean Whether this is an enforce (die)
1328 private function warnOrDie( $msg, $enforceLimits = false ) {
1329 if ( $enforceLimits ) {
1330 $this->dieUsage( $msg, 'integeroutofrange' );
1333 $this->setWarning( $msg );
1337 * Truncate an array to a certain length.
1338 * @param array $arr Array to truncate
1339 * @param int $limit Maximum length
1340 * @return bool True if the array was truncated, false otherwise
1342 public static function truncateArray( &$arr, $limit ) {
1344 while ( count( $arr ) > $limit ) {
1353 * Throw a UsageException, which will (if uncaught) call the main module's
1354 * error handler and die with an error message.
1356 * @param string $description One-line human-readable description of the
1357 * error condition, e.g., "The API requires a valid action parameter"
1358 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1359 * automated identification of the error, e.g., 'unknown_action'
1360 * @param int $httpRespCode HTTP response code
1361 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1362 * @throws UsageException
1364 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1365 Profiler
::instance()->close();
1366 throw new UsageException(
1368 $this->encodeParamName( $errorCode ),
1375 * Get error (as code, string) from a Status object.
1378 * @param Status $status Status object
1379 * @return array of code and error string
1381 public function getErrorFromStatus( $status ) {
1382 if ( $status->isGood() ) {
1383 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1386 $errors = $status->getErrorsArray();
1388 // No errors? Assume the warnings should be treated as errors
1389 $errors = $status->getWarningsArray();
1392 // Still no errors? Punt
1393 $errors = array( array( 'unknownerror-nocode' ) );
1396 // Cannot use dieUsageMsg() because extensions might return custom
1398 if ( $errors[0] instanceof Message
) {
1400 $code = $msg->getKey();
1402 $code = array_shift( $errors[0] );
1403 $msg = wfMessage( $code, $errors[0] );
1405 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1406 // Translate message to code, for backwards compatability
1407 $code = ApiBase
::$messageMap[$code]['code'];
1410 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1414 * Throw a UsageException based on the errors in the Status object.
1417 * @param Status $status Status object
1418 * @throws MWException
1420 public function dieStatus( $status ) {
1422 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1423 $this->dieUsage( $msg, $code );
1426 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1428 * Array that maps message keys to error messages. $1 and friends are replaced.
1430 public static $messageMap = array(
1431 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1432 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1433 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1435 // Messages from Title::getUserPermissionsErrors()
1436 'ns-specialprotected' => array(
1437 'code' => 'unsupportednamespace',
1438 'info' => "Pages in the Special namespace can't be edited"
1440 'protectedinterface' => array(
1441 'code' => 'protectednamespace-interface',
1442 'info' => "You're not allowed to edit interface messages"
1444 'namespaceprotected' => array(
1445 'code' => 'protectednamespace',
1446 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1448 'customcssprotected' => array(
1449 'code' => 'customcssprotected',
1450 'info' => "You're not allowed to edit custom CSS pages"
1452 'customjsprotected' => array(
1453 'code' => 'customjsprotected',
1454 'info' => "You're not allowed to edit custom JavaScript pages"
1456 'cascadeprotected' => array(
1457 'code' => 'cascadeprotected',
1458 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1460 'protectedpagetext' => array(
1461 'code' => 'protectedpage',
1462 'info' => "The \"\$1\" right is required to edit this page"
1464 'protect-cantedit' => array(
1465 'code' => 'cantedit',
1466 'info' => "You can't protect this page because you can't edit it"
1468 'badaccess-group0' => array(
1469 'code' => 'permissiondenied',
1470 'info' => "Permission denied"
1471 ), // Generic permission denied message
1472 'badaccess-groups' => array(
1473 'code' => 'permissiondenied',
1474 'info' => "Permission denied"
1476 'titleprotected' => array(
1477 'code' => 'protectedtitle',
1478 'info' => "This title has been protected from creation"
1480 'nocreate-loggedin' => array(
1481 'code' => 'cantcreate',
1482 'info' => "You don't have permission to create new pages"
1484 'nocreatetext' => array(
1485 'code' => 'cantcreate-anon',
1486 'info' => "Anonymous users can't create new pages"
1488 'movenologintext' => array(
1489 'code' => 'cantmove-anon',
1490 'info' => "Anonymous users can't move pages"
1492 'movenotallowed' => array(
1493 'code' => 'cantmove',
1494 'info' => "You don't have permission to move pages"
1496 'confirmedittext' => array(
1497 'code' => 'confirmemail',
1498 'info' => "You must confirm your email address before you can edit"
1500 'blockedtext' => array(
1501 'code' => 'blocked',
1502 'info' => "You have been blocked from editing"
1504 'autoblockedtext' => array(
1505 'code' => 'autoblocked',
1506 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1509 // Miscellaneous interface messages
1510 'actionthrottledtext' => array(
1511 'code' => 'ratelimited',
1512 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1514 'alreadyrolled' => array(
1515 'code' => 'alreadyrolled',
1516 'info' => "The page you tried to rollback was already rolled back"
1518 'cantrollback' => array(
1519 'code' => 'onlyauthor',
1520 'info' => "The page you tried to rollback only has one author"
1522 'readonlytext' => array(
1523 'code' => 'readonly',
1524 'info' => "The wiki is currently in read-only mode"
1526 'sessionfailure' => array(
1527 'code' => 'badtoken',
1528 'info' => "Invalid token" ),
1529 'cannotdelete' => array(
1530 'code' => 'cantdelete',
1531 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1533 'notanarticle' => array(
1534 'code' => 'missingtitle',
1535 'info' => "The page you requested doesn't exist"
1537 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1539 'immobile_namespace' => array(
1540 'code' => 'immobilenamespace',
1541 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1543 'articleexists' => array(
1544 'code' => 'articleexists',
1545 'info' => "The destination article already exists and is not a redirect to the source article"
1547 'protectedpage' => array(
1548 'code' => 'protectedpage',
1549 'info' => "You don't have permission to perform this move"
1551 'hookaborted' => array(
1552 'code' => 'hookaborted',
1553 'info' => "The modification you tried to make was aborted by an extension hook"
1555 'cantmove-titleprotected' => array(
1556 'code' => 'protectedtitle',
1557 'info' => "The destination article has been protected from creation"
1559 'imagenocrossnamespace' => array(
1560 'code' => 'nonfilenamespace',
1561 'info' => "Can't move a file to a non-file namespace"
1563 'imagetypemismatch' => array(
1564 'code' => 'filetypemismatch',
1565 'info' => "The new file extension doesn't match its type"
1567 // 'badarticleerror' => shouldn't happen
1568 // 'badtitletext' => shouldn't happen
1569 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1570 'range_block_disabled' => array(
1571 'code' => 'rangedisabled',
1572 'info' => "Blocking IP ranges has been disabled"
1574 'nosuchusershort' => array(
1575 'code' => 'nosuchuser',
1576 'info' => "The user you specified doesn't exist"
1578 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1579 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1580 'ipb_already_blocked' => array(
1581 'code' => 'alreadyblocked',
1582 'info' => "The user you tried to block was already blocked"
1584 'ipb_blocked_as_range' => array(
1585 'code' => 'blockedasrange',
1586 '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."
1588 'ipb_cant_unblock' => array(
1589 'code' => 'cantunblock',
1590 'info' => "The block you specified was not found. It may have been unblocked already"
1592 'mailnologin' => array(
1593 'code' => 'cantsend',
1594 '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"
1596 'ipbblocked' => array(
1597 'code' => 'ipbblocked',
1598 'info' => 'You cannot block or unblock users while you are yourself blocked'
1600 'ipbnounblockself' => array(
1601 'code' => 'ipbnounblockself',
1602 'info' => 'You are not allowed to unblock yourself'
1604 'usermaildisabled' => array(
1605 'code' => 'usermaildisabled',
1606 'info' => "User email has been disabled"
1608 'blockedemailuser' => array(
1609 'code' => 'blockedfrommail',
1610 'info' => "You have been blocked from sending email"
1612 'notarget' => array(
1613 'code' => 'notarget',
1614 'info' => "You have not specified a valid target for this action"
1617 'code' => 'noemail',
1618 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1620 'rcpatroldisabled' => array(
1621 'code' => 'patroldisabled',
1622 'info' => "Patrolling is disabled on this wiki"
1624 'markedaspatrollederror-noautopatrol' => array(
1625 'code' => 'noautopatrol',
1626 'info' => "You don't have permission to patrol your own changes"
1628 'delete-toobig' => array(
1629 'code' => 'bigdelete',
1630 'info' => "You can't delete this page because it has more than \$1 revisions"
1632 'movenotallowedfile' => array(
1633 'code' => 'cantmovefile',
1634 'info' => "You don't have permission to move files"
1636 'userrights-no-interwiki' => array(
1637 'code' => 'nointerwikiuserrights',
1638 'info' => "You don't have permission to change user rights on other wikis"
1640 'userrights-nodatabase' => array(
1641 'code' => 'nosuchdatabase',
1642 'info' => "Database \"\$1\" does not exist or is not local"
1644 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1645 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1646 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1647 'import-rootpage-invalid' => array(
1648 'code' => 'import-rootpage-invalid',
1649 'info' => 'Root page is an invalid title'
1651 'import-rootpage-nosubpage' => array(
1652 'code' => 'import-rootpage-nosubpage',
1653 'info' => 'Namespace "$1" of the root page does not allow subpages'
1656 // API-specific messages
1657 'readrequired' => array(
1658 'code' => 'readapidenied',
1659 'info' => "You need read permission to use this module"
1661 'writedisabled' => array(
1662 'code' => 'noapiwrite',
1663 '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"
1665 'writerequired' => array(
1666 'code' => 'writeapidenied',
1667 'info' => "You're not allowed to edit this wiki through the API"
1669 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1670 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1671 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1672 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1673 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1674 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1675 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1676 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1677 'create-titleexists' => array(
1678 'code' => 'create-titleexists',
1679 'info' => "Existing titles can't be protected with 'create'"
1681 'missingtitle-createonly' => array(
1682 'code' => 'missingtitle-createonly',
1683 'info' => "Missing titles can only be protected with 'create'"
1685 'cantblock' => array( 'code' => 'cantblock',
1686 'info' => "You don't have permission to block users"
1688 'canthide' => array(
1689 'code' => 'canthide',
1690 'info' => "You don't have permission to hide user names from the block log"
1692 'cantblock-email' => array(
1693 'code' => 'cantblock-email',
1694 'info' => "You don't have permission to block users from sending email through the wiki"
1696 'unblock-notarget' => array(
1697 'code' => 'notarget',
1698 'info' => "Either the id or the user parameter must be set"
1700 'unblock-idanduser' => array(
1701 'code' => 'idanduser',
1702 'info' => "The id and user parameters can't be used together"
1704 'cantunblock' => array(
1705 'code' => 'permissiondenied',
1706 'info' => "You don't have permission to unblock users"
1708 'cannotundelete' => array(
1709 'code' => 'cantundelete',
1710 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1712 'permdenied-undelete' => array(
1713 'code' => 'permissiondenied',
1714 'info' => "You don't have permission to restore deleted revisions"
1716 'createonly-exists' => array(
1717 'code' => 'articleexists',
1718 'info' => "The article you tried to create has been created already"
1720 'nocreate-missing' => array(
1721 'code' => 'missingtitle',
1722 'info' => "The article you tried to edit doesn't exist"
1724 'nosuchrcid' => array(
1725 'code' => 'nosuchrcid',
1726 'info' => "There is no change with rcid \"\$1\""
1728 'protect-invalidaction' => array(
1729 'code' => 'protect-invalidaction',
1730 'info' => "Invalid protection type \"\$1\""
1732 'protect-invalidlevel' => array(
1733 'code' => 'protect-invalidlevel',
1734 'info' => "Invalid protection level \"\$1\""
1736 'toofewexpiries' => array(
1737 'code' => 'toofewexpiries',
1738 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1740 'cantimport' => array(
1741 'code' => 'cantimport',
1742 'info' => "You don't have permission to import pages"
1744 'cantimport-upload' => array(
1745 'code' => 'cantimport-upload',
1746 'info' => "You don't have permission to import uploaded pages"
1748 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1749 'importuploaderrorsize' => array(
1750 'code' => 'filetoobig',
1751 'info' => 'The file you uploaded is bigger than the maximum upload size'
1753 'importuploaderrorpartial' => array(
1754 'code' => 'partialupload',
1755 'info' => 'The file was only partially uploaded'
1757 'importuploaderrortemp' => array(
1758 'code' => 'notempdir',
1759 'info' => 'The temporary upload directory is missing'
1761 'importcantopen' => array(
1762 'code' => 'cantopenfile',
1763 'info' => "Couldn't open the uploaded file"
1765 'import-noarticle' => array(
1766 'code' => 'badinterwiki',
1767 'info' => 'Invalid interwiki title specified'
1769 'importbadinterwiki' => array(
1770 'code' => 'badinterwiki',
1771 'info' => 'Invalid interwiki title specified'
1773 'import-unknownerror' => array(
1774 'code' => 'import-unknownerror',
1775 'info' => "Unknown error on import: \"\$1\""
1777 'cantoverwrite-sharedfile' => array(
1778 'code' => 'cantoverwrite-sharedfile',
1779 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1781 'sharedfile-exists' => array(
1782 'code' => 'fileexists-sharedrepo-perm',
1783 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1785 'mustbeposted' => array(
1786 'code' => 'mustbeposted',
1787 'info' => "The \$1 module requires a POST request"
1791 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1793 'specialpage-cantexecute' => array(
1794 'code' => 'specialpage-cantexecute',
1795 'info' => "You don't have permission to view the results of this special page"
1797 'invalidoldimage' => array(
1798 'code' => 'invalidoldimage',
1799 'info' => 'The oldimage parameter has invalid format'
1801 'nodeleteablefile' => array(
1802 'code' => 'nodeleteablefile',
1803 'info' => 'No such old version of the file'
1805 'fileexists-forbidden' => array(
1806 'code' => 'fileexists-forbidden',
1807 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1809 'fileexists-shared-forbidden' => array(
1810 'code' => 'fileexists-shared-forbidden',
1811 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1813 'filerevert-badversion' => array(
1814 'code' => 'filerevert-badversion',
1815 'info' => 'There is no previous local version of this file with the provided timestamp.'
1818 // ApiEditPage messages
1819 'noimageredirect-anon' => array(
1820 'code' => 'noimageredirect-anon',
1821 'info' => "Anonymous users can't create image redirects"
1823 'noimageredirect-logged' => array(
1824 'code' => 'noimageredirect',
1825 'info' => "You don't have permission to create image redirects"
1827 'spamdetected' => array(
1828 'code' => 'spamdetected',
1829 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1831 'contenttoobig' => array(
1832 'code' => 'contenttoobig',
1833 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1835 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1836 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1837 'wasdeleted' => array(
1838 'code' => 'pagedeleted',
1839 'info' => "The page has been deleted since you fetched its timestamp"
1841 'blankpage' => array(
1842 'code' => 'emptypage',
1843 'info' => "Creating new, empty pages is not allowed"
1845 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1846 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1847 'missingtext' => array(
1849 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1851 'emptynewsection' => array(
1852 'code' => 'emptynewsection',
1853 'info' => 'Creating empty new sections is not possible.'
1855 'revwrongpage' => array(
1856 'code' => 'revwrongpage',
1857 'info' => "r\$1 is not a revision of \"\$2\""
1859 'undo-failure' => array(
1860 'code' => 'undofailure',
1861 'info' => 'Undo failed due to conflicting intermediate edits'
1864 // Messages from WikiPage::doEit()
1865 'edit-hook-aborted' => array(
1866 'code' => 'edit-hook-aborted',
1867 'info' => "Your edit was aborted by an ArticleSave hook"
1869 'edit-gone-missing' => array(
1870 'code' => 'edit-gone-missing',
1871 'info' => "The page you tried to edit doesn't seem to exist anymore"
1873 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1874 'edit-already-exists' => array(
1875 'code' => 'edit-already-exists',
1876 'info' => 'It seems the page you tried to create already exist'
1880 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1881 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1882 'uploaddisabled' => array(
1883 'code' => 'uploaddisabled',
1884 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1886 'copyuploaddisabled' => array(
1887 'code' => 'copyuploaddisabled',
1888 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1890 'copyuploadbaddomain' => array(
1891 'code' => 'copyuploadbaddomain',
1892 'info' => 'Uploads by URL are not allowed from this domain.'
1894 'copyuploadbadurl' => array(
1895 'code' => 'copyuploadbadurl',
1896 'info' => 'Upload not allowed from this URL.'
1899 'filename-tooshort' => array(
1900 'code' => 'filename-tooshort',
1901 'info' => 'The filename is too short'
1903 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1904 'illegal-filename' => array(
1905 'code' => 'illegal-filename',
1906 'info' => 'The filename is not allowed'
1908 'filetype-missing' => array(
1909 'code' => 'filetype-missing',
1910 'info' => 'The file is missing an extension'
1913 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1915 // @codingStandardsIgnoreEnd
1918 * Helper function for readonly errors
1920 public function dieReadOnly() {
1921 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1922 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1923 array( 'readonlyreason' => wfReadOnlyReason() ) );
1927 * Output the error message related to a certain array
1928 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1930 public function dieUsageMsg( $error ) {
1931 # most of the time we send a 1 element, so we might as well send it as
1932 # a string and make this an array here.
1933 if ( is_string( $error ) ) {
1934 $error = array( $error );
1936 $parsed = $this->parseMsg( $error );
1937 $this->dieUsage( $parsed['info'], $parsed['code'] );
1941 * Will only set a warning instead of failing if the global $wgDebugAPI
1942 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1943 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1946 public function dieUsageMsgOrDebug( $error ) {
1948 if ( $wgDebugAPI !== true ) {
1949 $this->dieUsageMsg( $error );
1952 if ( is_string( $error ) ) {
1953 $error = array( $error );
1956 $parsed = $this->parseMsg( $error );
1957 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1961 * Die with the $prefix.'badcontinue' error. This call is common enough to
1962 * make it into the base method.
1963 * @param $condition boolean will only die if this value is true
1966 protected function dieContinueUsageIf( $condition ) {
1969 'Invalid continue param. You should pass the original value returned by the previous query',
1975 * Return the error message related to a certain array
1976 * @param array $error Element of a getUserPermissionsErrors()-style array
1977 * @return array('code' => code, 'info' => info)
1979 public function parseMsg( $error ) {
1980 $error = (array)$error; // It seems strings sometimes make their way in here
1981 $key = array_shift( $error );
1983 // Check whether the error array was nested
1984 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1985 if ( is_array( $key ) ) {
1987 $key = array_shift( $error );
1990 if ( isset( self
::$messageMap[$key] ) ) {
1992 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1993 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1997 // If the key isn't present, throw an "unknown error"
1998 return $this->parseMsg( array( 'unknownerror', $key ) );
2002 * Internal code errors should be reported with this method
2003 * @param string $method Method or function name
2004 * @param string $message Error message
2005 * @throws MWException
2007 protected static function dieDebug( $method, $message ) {
2008 throw new MWException( "Internal error in $method: $message" );
2012 * Indicates if this module needs maxlag to be checked
2015 public function shouldCheckMaxlag() {
2020 * Indicates whether this module requires read rights
2023 public function isReadMode() {
2028 * Indicates whether this module requires write mode
2031 public function isWriteMode() {
2036 * Indicates whether this module must be called with a POST request
2039 public function mustBePosted() {
2044 * Returns whether this module requires a token to execute
2045 * It is used to show possible errors in action=paraminfo
2049 public function needsToken() {
2054 * Returns the token salt if there is one,
2055 * '' if the module doesn't require a salt,
2056 * else false if the module doesn't need a token
2057 * You have also to override needsToken()
2058 * Value is passed to User::getEditToken
2059 * @return bool|string|array
2061 public function getTokenSalt() {
2066 * Gets the user for whom to get the watchlist
2068 * @param $params array
2071 public function getWatchlistUser( $params ) {
2072 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2073 $user = User
::newFromName( $params['owner'], false );
2074 if ( !( $user && $user->getId() ) ) {
2075 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2077 $token = $user->getOption( 'watchlisttoken' );
2078 if ( $token == '' ||
$token != $params['token'] ) {
2080 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2085 if ( !$this->getUser()->isLoggedIn() ) {
2086 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2088 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2089 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2091 $user = $this->getUser();
2098 * @return bool|string|array Returns a false if the module has no help URL,
2099 * else returns a (array of) string
2101 public function getHelpUrls() {
2106 * Returns a list of all possible errors returned by the module
2108 * Don't call this function directly: use getFinalPossibleErrors() to allow
2109 * hooks to modify parameters as needed.
2111 * @return array in the format of array( key, param1, param2, ... )
2112 * or array( 'code' => ..., 'info' => ... )
2114 public function getPossibleErrors() {
2117 $params = $this->getFinalParams();
2119 foreach ( $params as $paramName => $paramSettings ) {
2120 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] )
2121 && $paramSettings[ApiBase
::PARAM_REQUIRED
]
2123 $ret[] = array( 'missingparam', $paramName );
2126 if ( array_key_exists( 'continue', $params ) ) {
2128 'code' => 'badcontinue',
2129 'info' => 'Invalid continue param. You should pass the ' .
2130 'original value returned by the previous query'
2135 if ( $this->mustBePosted() ) {
2136 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2139 if ( $this->isReadMode() ) {
2140 $ret[] = array( 'readrequired' );
2143 if ( $this->isWriteMode() ) {
2144 $ret[] = array( 'writerequired' );
2145 $ret[] = array( 'writedisabled' );
2148 if ( $this->needsToken() ) {
2149 if ( !isset( $params['token'][ApiBase
::PARAM_REQUIRED
] )
2150 ||
!$params['token'][ApiBase
::PARAM_REQUIRED
]
2152 // Add token as possible missing parameter, if not already done
2153 $ret[] = array( 'missingparam', 'token' );
2155 $ret[] = array( 'sessionfailure' );
2162 * Get final list of possible errors, after hooks have had a chance to
2163 * tweak it as needed.
2168 public function getFinalPossibleErrors() {
2169 $possibleErrors = $this->getPossibleErrors();
2170 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2172 return $possibleErrors;
2176 * Parses a list of errors into a standardised format
2177 * @param array $errors List of errors. Items can be in the for
2178 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2179 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2181 public function parseErrors( $errors ) {
2184 foreach ( $errors as $row ) {
2185 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2188 $ret[] = $this->parseMsg( $row );
2196 * Profiling: total module execution time
2198 private $mTimeIn = 0, $mModuleTime = 0;
2201 * Start module profiling
2203 public function profileIn() {
2204 if ( $this->mTimeIn
!== 0 ) {
2205 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2207 $this->mTimeIn
= microtime( true );
2208 wfProfileIn( $this->getModuleProfileName() );
2212 * End module profiling
2214 public function profileOut() {
2215 if ( $this->mTimeIn
=== 0 ) {
2216 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2218 if ( $this->mDBTimeIn
!== 0 ) {
2221 'Must be called after database profiling is done with profileDBOut()'
2225 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2227 wfProfileOut( $this->getModuleProfileName() );
2231 * When modules crash, sometimes it is needed to do a profileOut() regardless
2232 * of the profiling state the module was in. This method does such cleanup.
2234 public function safeProfileOut() {
2235 if ( $this->mTimeIn
!== 0 ) {
2236 if ( $this->mDBTimeIn
!== 0 ) {
2237 $this->profileDBOut();
2239 $this->profileOut();
2244 * Total time the module was executed
2247 public function getProfileTime() {
2248 if ( $this->mTimeIn
!== 0 ) {
2249 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2252 return $this->mModuleTime
;
2256 * Profiling: database execution time
2258 private $mDBTimeIn = 0, $mDBTime = 0;
2261 * Start module profiling
2263 public function profileDBIn() {
2264 if ( $this->mTimeIn
=== 0 ) {
2267 'Must be called while profiling the entire module with profileIn()'
2270 if ( $this->mDBTimeIn
!== 0 ) {
2271 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2273 $this->mDBTimeIn
= microtime( true );
2274 wfProfileIn( $this->getModuleProfileName( true ) );
2278 * End database profiling
2280 public function profileDBOut() {
2281 if ( $this->mTimeIn
=== 0 ) {
2282 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2283 'the entire module with profileIn()' );
2285 if ( $this->mDBTimeIn
=== 0 ) {
2286 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2289 $time = microtime( true ) - $this->mDBTimeIn
;
2290 $this->mDBTimeIn
= 0;
2292 $this->mDBTime +
= $time;
2293 $this->getMain()->mDBTime +
= $time;
2294 wfProfileOut( $this->getModuleProfileName( true ) );
2298 * Total time the module used the database
2301 public function getProfileDBTime() {
2302 if ( $this->mDBTimeIn
!== 0 ) {
2303 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2306 return $this->mDBTime
;
2310 * Gets a default slave database connection object
2311 * @return DatabaseBase
2313 protected function getDB() {
2314 if ( !isset( $this->mSlaveDB
) ) {
2315 $this->profileDBIn();
2316 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2317 $this->profileDBOut();
2320 return $this->mSlaveDB
;
2324 * Debugging function that prints a value and an optional backtrace
2325 * @param $value mixed Value to print
2326 * @param string $name Description of the printed value
2327 * @param bool $backtrace If true, print a backtrace
2329 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2330 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2331 var_export( $value );
2333 print "\n" . wfBacktrace();