5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT
= 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST
= 'LIST';
74 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE
= 1;
78 const LIMIT_BIG1
= 500; // Fast query, std user limit
79 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1
= 50; // Slow query, std user limit
81 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
88 const GET_VALUES_FOR_HELP
= 1;
93 private $mModuleName, $mModulePrefix;
94 private $mSlaveDB = null;
95 private $mParamCache = array();
98 * @param ApiMain $mainModule
99 * @param string $moduleName Name of this module
100 * @param string $modulePrefix Prefix to use for parameter names
102 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
103 $this->mMainModule
= $mainModule;
104 $this->mModuleName
= $moduleName;
105 $this->mModulePrefix
= $modulePrefix;
107 if ( !$this->isMain() ) {
108 $this->setContext( $mainModule->getContext() );
112 /*****************************************************************************
114 *****************************************************************************/
117 * Evaluates the parameters, performs the requested query, and sets up
118 * the result. Concrete implementations of ApiBase must override this
119 * method to provide whatever functionality their module offers.
120 * Implementations must not produce any output on their own and are not
121 * expected to handle any errors.
123 * The execute() method will be invoked directly by ApiMain immediately
124 * before the result of the module is output. Aside from the
125 * constructor, implementations should assume that no other methods
126 * will be called externally on the module before the result is
129 * The result data should be stored in the ApiResult object available
130 * through getResult().
132 abstract public function execute();
135 * Returns a string that identifies the version of the extending class.
136 * Typically includes the class name, the svn revision, timestamp, and
137 * last author. Usually done with SVN's Id keyword
139 * @deprecated since 1.21, version string is no longer supported
141 public function getVersion() {
142 wfDeprecated( __METHOD__
, '1.21' );
148 * Get the name of the module being executed by this instance
151 public function getModuleName() {
152 return $this->mModuleName
;
156 * Get the module manager, or null if this module has no sub-modules
158 * @return ApiModuleManager
160 public function getModuleManager() {
165 * Get parameter prefix (usually two letters or an empty string).
168 public function getModulePrefix() {
169 return $this->mModulePrefix
;
173 * Get the name of the module as shown in the profiler log
175 * @param DatabaseBase|bool $db
179 public function getModuleProfileName( $db = false ) {
181 return 'API:' . $this->mModuleName
. '-DB';
184 return 'API:' . $this->mModuleName
;
188 * Get the main module
191 public function getMain() {
192 return $this->mMainModule
;
196 * Returns true if this module is the main module ($this === $this->mMainModule),
200 public function isMain() {
201 return $this === $this->mMainModule
;
205 * Get the result object
208 public function getResult() {
209 // Main module has getResult() method overridden
210 // Safety - avoid infinite loop:
211 if ( $this->isMain() ) {
212 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
215 return $this->getMain()->getResult();
219 * Get the result data array (read-only)
222 public function getResultData() {
223 return $this->getResult()->getData();
227 * Create a new RequestContext object to use e.g. for calls to other parts
229 * The object will have the WebRequest and the User object set to the ones
230 * used in this instance.
232 * @deprecated since 1.19 use getContext to get the current context
233 * @return DerivativeContext
235 public function createContext() {
236 wfDeprecated( __METHOD__
, '1.19' );
238 return new DerivativeContext( $this->getContext() );
242 * Set warning section for this module. Users should monitor this
243 * section to notice any changes in API. Multiple calls to this
244 * function will result in the warning messages being separated by
246 * @param string $warning Warning message
248 public function setWarning( $warning ) {
249 $result = $this->getResult();
250 $data = $result->getData();
251 $moduleName = $this->getModuleName();
252 if ( isset( $data['warnings'][$moduleName] ) ) {
253 // Don't add duplicate warnings
254 $oldWarning = $data['warnings'][$moduleName]['*'];
255 $warnPos = strpos( $oldWarning, $warning );
256 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
257 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
258 // Check if $warning is followed by "\n" or the end of the $oldWarning
259 $warnPos +
= strlen( $warning );
260 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
264 // If there is a warning already, append it to the existing one
265 $warning = "$oldWarning\n$warning";
268 ApiResult
::setContent( $msg, $warning );
269 $result->disableSizeCheck();
270 $result->addValue( 'warnings', $moduleName,
271 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
272 $result->enableSizeCheck();
276 * If the module may only be used with a certain format module,
277 * it should override this method to return an instance of that formatter.
278 * A value of null means the default format will be used.
279 * @return mixed Instance of a derived class of ApiFormatBase, or null
281 public function getCustomPrinter() {
286 * Generates help message for this module, or false if there is no description
287 * @return string|bool
289 public function makeHelpMsg() {
290 static $lnPrfx = "\n ";
292 $msg = $this->getFinalDescription();
294 if ( $msg !== false ) {
296 if ( !is_array( $msg ) ) {
301 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
303 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
305 if ( $this->isReadMode() ) {
306 $msg .= "\nThis module requires read rights";
308 if ( $this->isWriteMode() ) {
309 $msg .= "\nThis module requires write rights";
311 if ( $this->mustBePosted() ) {
312 $msg .= "\nThis module only accepts POST requests";
314 if ( $this->isReadMode() ||
$this->isWriteMode() ||
315 $this->mustBePosted()
321 $paramsMsg = $this->makeHelpMsgParameters();
322 if ( $paramsMsg !== false ) {
323 $msg .= "Parameters:\n$paramsMsg";
326 $examples = $this->getExamples();
328 if ( !is_array( $examples ) ) {
333 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
334 foreach ( $examples as $k => $v ) {
335 if ( is_numeric( $k ) ) {
338 if ( is_array( $v ) ) {
339 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
344 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
354 * @param string $item
357 private function indentExampleText( $item ) {
362 * @param string $prefix Text to split output items
363 * @param string $title What is being output
364 * @param string|array $input
367 protected function makeHelpArrayToString( $prefix, $title, $input ) {
368 if ( $input === false ) {
371 if ( !is_array( $input ) ) {
372 $input = array( $input );
375 if ( count( $input ) > 0 ) {
377 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
381 $msg .= implode( $prefix, $input ) . "\n";
390 * Generates the parameter descriptions for this module, to be displayed in the
392 * @return string|bool
394 public function makeHelpMsgParameters() {
395 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
398 $paramsDescription = $this->getFinalParamDescription();
400 $paramPrefix = "\n" . str_repeat( ' ', 24 );
401 $descWordwrap = "\n" . str_repeat( ' ', 28 );
402 foreach ( $params as $paramName => $paramSettings ) {
403 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
404 if ( is_array( $desc ) ) {
405 $desc = implode( $paramPrefix, $desc );
409 if ( !is_array( $paramSettings ) ) {
410 $paramSettings = array(
411 self
::PARAM_DFLT
=> $paramSettings,
415 //handle missing type
416 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
417 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
418 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
420 if ( is_bool( $dflt ) ) {
421 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
422 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
423 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
424 } elseif ( is_int( $dflt ) ) {
425 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
429 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
430 && $paramSettings[self
::PARAM_DEPRECATED
]
432 $desc = "DEPRECATED! $desc";
435 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
436 && $paramSettings[self
::PARAM_REQUIRED
]
438 $desc .= $paramPrefix . "This parameter is required";
441 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
442 ?
$paramSettings[self
::PARAM_TYPE
]
444 if ( isset( $type ) ) {
445 $hintPipeSeparated = true;
446 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
447 ?
$paramSettings[self
::PARAM_ISMULTI
]
450 $prompt = 'Values (separate with \'|\'): ';
452 $prompt = 'One value: ';
455 if ( is_array( $type ) ) {
458 foreach ( $type as $t ) {
460 $nothingPrompt = 'Can be empty, or ';
465 $desc .= $paramPrefix . $nothingPrompt . $prompt;
466 $choicesstring = implode( ', ', $choices );
467 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
468 $hintPipeSeparated = false;
472 // Special handling because namespaces are
473 // type-limited, yet they are not given
474 $desc .= $paramPrefix . $prompt;
475 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
476 100, $descWordwrap );
477 $hintPipeSeparated = false;
480 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
481 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
482 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
487 $s = $multi ?
's' : '';
488 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
489 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
490 if ( $hasMin ||
$hasMax ) {
492 $intRangeStr = "The value$s must be no less than " .
493 "{$paramSettings[self::PARAM_MIN]}";
494 } elseif ( !$hasMin ) {
495 $intRangeStr = "The value$s must be no more than " .
496 "{$paramSettings[self::PARAM_MAX]}";
498 $intRangeStr = "The value$s must be between " .
499 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
502 $desc .= $paramPrefix . $intRangeStr;
506 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
512 if ( $hintPipeSeparated ) {
513 $desc .= $paramPrefix . "Separate values with '|'";
516 $isArray = is_array( $type );
518 ||
$isArray && count( $type ) > self
::LIMIT_SML1
520 $desc .= $paramPrefix . "Maximum number of values " .
521 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
526 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
527 if ( !is_null( $default ) && $default !== false ) {
528 $desc .= $paramPrefix . "Default: $default";
531 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
541 * Returns the description string for this module
542 * @return string|array
544 protected function getDescription() {
549 * Returns usage examples for this module. Return false if no examples are available.
550 * @return bool|string|array
552 protected function getExamples() {
557 * Returns an array of allowed parameters (parameter name) => (default
558 * value) or (parameter name) => (array with PARAM_* constants as keys)
559 * Don't call this function directly: use getFinalParams() to allow
560 * hooks to modify parameters as needed.
562 * Some derived classes may choose to handle an integer $flags parameter
563 * in the overriding methods. Callers of this method can pass zero or
564 * more OR-ed flags like GET_VALUES_FOR_HELP.
568 protected function getAllowedParams( /* $flags = 0 */ ) {
569 // int $flags is not declared because it causes "Strict standards"
570 // warning. Most derived classes do not implement it.
575 * Returns an array of parameter descriptions.
576 * Don't call this function directly: use getFinalParamDescription() to
577 * allow hooks to modify descriptions as needed.
578 * @return array|bool False on no parameter descriptions
580 protected function getParamDescription() {
585 * Get final list of parameters, after hooks have had a chance to
586 * tweak it as needed.
588 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
589 * @return array|bool False on no parameters
590 * @since 1.21 $flags param added
592 public function getFinalParams( $flags = 0 ) {
593 $params = $this->getAllowedParams( $flags );
594 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
600 * Get final parameter descriptions, after hooks have had a chance to tweak it as
603 * @return array|bool False on no parameter descriptions
605 public function getFinalParamDescription() {
606 $desc = $this->getParamDescription();
607 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
613 * Returns possible properties in the result, grouped by the value of the prop parameter
616 * Properties that are shown always are in a group with empty string as a key.
617 * Properties that can be shown by several values of prop are included multiple times.
618 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
619 * those on the root object are under the key PROP_ROOT.
620 * The array can also contain a boolean under the key PROP_LIST,
621 * indicating whether the result is a list.
623 * Don't call this function directly: use getFinalResultProperties() to
624 * allow hooks to modify descriptions as needed.
626 * @return array|bool False on no properties
628 protected function getResultProperties() {
633 * Get final possible result properties, after hooks have had a chance to tweak it as
638 public function getFinalResultProperties() {
639 $properties = $this->getResultProperties();
640 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
646 * Add token properties to the array used by getResultProperties,
647 * based on a token functions mapping.
648 * @param array $props
649 * @param array $tokenFunctions
651 protected static function addTokenProperties( &$props, $tokenFunctions ) {
652 foreach ( array_keys( $tokenFunctions ) as $token ) {
653 $props[''][$token . 'token'] = array(
654 ApiBase
::PROP_TYPE
=> 'string',
655 ApiBase
::PROP_NULLABLE
=> true
661 * Get final module description, after hooks have had a chance to tweak it as
664 * @return array|bool False on no parameters
666 public function getFinalDescription() {
667 $desc = $this->getDescription();
668 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
674 * This method mangles parameter name based on the prefix supplied to the constructor.
675 * Override this method to change parameter name during runtime
676 * @param string $paramName Parameter name
677 * @return string Prefixed parameter name
679 public function encodeParamName( $paramName ) {
680 return $this->mModulePrefix
. $paramName;
684 * Using getAllowedParams(), this function makes an array of the values
685 * provided by the user, with key being the name of the variable, and
686 * value - validated value from user or default. limits will not be
687 * parsed if $parseLimit is set to false; use this when the max
688 * limit is not definitive yet, e.g. when getting revisions.
689 * @param bool $parseLimit True by default
692 public function extractRequestParams( $parseLimit = true ) {
693 // Cache parameters, for performance and to avoid bug 24564.
694 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
695 $params = $this->getFinalParams();
698 if ( $params ) { // getFinalParams() can return false
699 foreach ( $params as $paramName => $paramSettings ) {
700 $results[$paramName] = $this->getParameterFromSettings(
701 $paramName, $paramSettings, $parseLimit );
704 $this->mParamCache
[$parseLimit] = $results;
707 return $this->mParamCache
[$parseLimit];
711 * Get a value for the given parameter
712 * @param string $paramName Parameter name
713 * @param bool $parseLimit See extractRequestParams()
714 * @return mixed Parameter value
716 protected function getParameter( $paramName, $parseLimit = true ) {
717 $params = $this->getFinalParams();
718 $paramSettings = $params[$paramName];
720 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
724 * Die if none or more than one of a certain set of parameters is set and not false.
726 * Call getRequireOnlyOneParameterErrorMessages() to get a list of possible errors.
728 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
729 * @param string $required,... Names of parameters of which exactly one must be set
731 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
732 $required = func_get_args();
733 array_shift( $required );
734 $p = $this->getModulePrefix();
736 $intersection = array_intersect( array_keys( array_filter( $params,
737 array( $this, "parameterNotEmpty" ) ) ), $required );
739 if ( count( $intersection ) > 1 ) {
741 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
743 } elseif ( count( $intersection ) == 0 ) {
745 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
752 * Generates the possible errors requireOnlyOneParameter() can die with
754 * @param array $params
757 public function getRequireOnlyOneParameterErrorMessages( $params ) {
758 $p = $this->getModulePrefix();
759 $params = implode( ", {$p}", $params );
763 'code' => "{$p}missingparam",
764 'info' => "One of the parameters {$p}{$params} is required"
767 'code' => "{$p}invalidparammix",
768 'info' => "The parameters {$p}{$params} can not be used together"
774 * Die if more than one of a certain set of parameters is set and not false.
776 * Call getRequireMaxOneParameterErrorMessages() to get a list of possible errors.
778 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
779 * @param string $required,... Names of parameters of which at most one must be set
781 public function requireMaxOneParameter( $params, $required /*...*/ ) {
782 $required = func_get_args();
783 array_shift( $required );
784 $p = $this->getModulePrefix();
786 $intersection = array_intersect( array_keys( array_filter( $params,
787 array( $this, "parameterNotEmpty" ) ) ), $required );
789 if ( count( $intersection ) > 1 ) {
791 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
798 * Generates the possible error requireMaxOneParameter() can die with
800 * @param array $params
803 public function getRequireMaxOneParameterErrorMessages( $params ) {
804 $p = $this->getModulePrefix();
805 $params = implode( ", {$p}", $params );
809 'code' => "{$p}invalidparammix",
810 'info' => "The parameters {$p}{$params} can not be used together"
816 * Die if none of a certain set of parameters is set and not false.
818 * Call getRequireAtLeastOneParameterErrorMessages() to get a list of possible errors.
821 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
822 * @param string $required,... Names of parameters of which at least one must be set
824 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
825 $required = func_get_args();
826 array_shift( $required );
827 $p = $this->getModulePrefix();
829 $intersection = array_intersect(
830 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
834 if ( count( $intersection ) == 0 ) {
835 $this->dieUsage( "At least one of the parameters {$p}" .
836 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
841 * Generates the possible errors requireAtLeastOneParameter() can die with
844 * @param array $params Array of parameter key names
847 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
848 $p = $this->getModulePrefix();
849 $params = implode( ", {$p}", $params );
853 'code' => "{$p}missingparam",
854 'info' => "At least one of the parameters {$p}{$params} is required",
860 * Get a WikiPage object from a title or pageid param, if possible.
861 * Can die, if no param is set or if the title or page id is not valid.
863 * Call getTitleOrPageIdErrorMessage() to get a list of possible errors.
865 * @param array $params
866 * @param bool|string $load Whether load the object's state from the database:
867 * - false: don't load (if the pageid is given, it will still be loaded)
868 * - 'fromdb': load from a slave database
869 * - 'fromdbmaster': load from the master database
872 public function getTitleOrPageId( $params, $load = false ) {
873 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
876 if ( isset( $params['title'] ) ) {
877 $titleObj = Title
::newFromText( $params['title'] );
878 if ( !$titleObj ||
$titleObj->isExternal() ) {
879 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
881 if ( !$titleObj->canExist() ) {
882 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
884 $pageObj = WikiPage
::factory( $titleObj );
885 if ( $load !== false ) {
886 $pageObj->loadPageData( $load );
888 } elseif ( isset( $params['pageid'] ) ) {
889 if ( $load === false ) {
892 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
894 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
902 * Generates the possible error getTitleOrPageId() can die with
906 public function getTitleOrPageIdErrorMessage() {
908 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
910 array( 'invalidtitle', 'title' ),
911 array( 'nosuchpageid', 'pageid' ),
912 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
918 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
920 * @param object $x Parameter to check is not null/false
923 private function parameterNotEmpty( $x ) {
924 return !is_null( $x ) && $x !== false;
928 * Return true if we're to watch the page, false if not, null if no change.
929 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
930 * @param Title $titleObj The page under consideration
931 * @param string $userOption The user option to consider when $watchlist=preferences.
932 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
935 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
937 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
939 switch ( $watchlist ) {
947 # If the user is already watching, don't bother checking
948 if ( $userWatching ) {
951 # If no user option was passed, use watchdefault and watchcreations
952 if ( is_null( $userOption ) ) {
953 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
954 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
957 # Watch the article based on the user preference
958 return $this->getUser()->getBoolOption( $userOption );
961 return $userWatching;
964 return $userWatching;
969 * Set a watch (or unwatch) based the based on a watchlist parameter.
970 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
971 * @param Title $titleObj The article's title to change
972 * @param string $userOption The user option to consider when $watch=preferences
974 protected function setWatch( $watch, $titleObj, $userOption = null ) {
975 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
976 if ( $value === null ) {
980 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
984 * Using the settings determine the value for the given parameter
986 * @param string $paramName Parameter name
987 * @param array|mixed $paramSettings Default value or an array of settings
988 * using PARAM_* constants.
989 * @param bool $parseLimit Parse limit?
990 * @return mixed Parameter value
992 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
993 // Some classes may decide to change parameter names
994 $encParamName = $this->encodeParamName( $paramName );
996 if ( !is_array( $paramSettings ) ) {
997 $default = $paramSettings;
999 $type = gettype( $paramSettings );
1001 $deprecated = false;
1004 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1005 ?
$paramSettings[self
::PARAM_DFLT
]
1007 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1008 ?
$paramSettings[self
::PARAM_ISMULTI
]
1010 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1011 ?
$paramSettings[self
::PARAM_TYPE
]
1013 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1014 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1016 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1017 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1019 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1020 ?
$paramSettings[self
::PARAM_REQUIRED
]
1023 // When type is not given, and no choices, the type is the same as $default
1024 if ( !isset( $type ) ) {
1025 if ( isset( $default ) ) {
1026 $type = gettype( $default );
1028 $type = 'NULL'; // allow everything
1033 if ( $type == 'boolean' ) {
1034 if ( isset( $default ) && $default !== false ) {
1035 // Having a default value of anything other than 'false' is not allowed
1038 "Boolean param $encParamName's default is set to '$default'. " .
1039 "Boolean parameters must default to false."
1043 $value = $this->getMain()->getCheck( $encParamName );
1044 } elseif ( $type == 'upload' ) {
1045 if ( isset( $default ) ) {
1046 // Having a default value is not allowed
1049 "File upload param $encParamName's default is set to " .
1050 "'$default'. File upload parameters may not have a default." );
1053 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1055 $value = $this->getMain()->getUpload( $encParamName );
1056 if ( !$value->exists() ) {
1057 // This will get the value without trying to normalize it
1058 // (because trying to normalize a large binary file
1059 // accidentally uploaded as a field fails spectacularly)
1060 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1061 if ( $value !== null ) {
1063 "File upload param $encParamName is not a file upload; " .
1064 "be sure to use multipart/form-data for your POST and include " .
1065 "a filename in the Content-Disposition header.",
1066 "badupload_{$encParamName}"
1071 $value = $this->getMain()->getVal( $encParamName, $default );
1073 if ( isset( $value ) && $type == 'namespace' ) {
1074 $type = MWNamespace
::getValidNamespaces();
1078 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1079 $value = $this->parseMultiValue(
1083 is_array( $type ) ?
$type : null
1087 // More validation only when choices were not given
1088 // choices were validated in parseMultiValue()
1089 if ( isset( $value ) ) {
1090 if ( !is_array( $type ) ) {
1092 case 'NULL': // nothing to do
1095 if ( $required && $value === '' ) {
1096 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1099 case 'integer': // Force everything using intval() and optionally validate limits
1100 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1101 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1102 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1103 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1105 if ( is_array( $value ) ) {
1106 $value = array_map( 'intval', $value );
1107 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1108 foreach ( $value as &$v ) {
1109 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1113 $value = intval( $value );
1114 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1115 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1120 if ( !$parseLimit ) {
1121 // Don't do any validation whatsoever
1124 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1125 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1129 "MAX1 or MAX2 are not defined for the limit $encParamName"
1133 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1135 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1136 if ( $value == 'max' ) {
1137 $value = $this->getMain()->canApiHighLimits()
1138 ?
$paramSettings[self
::PARAM_MAX2
]
1139 : $paramSettings[self
::PARAM_MAX
];
1140 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1142 $value = intval( $value );
1143 $this->validateLimit(
1147 $paramSettings[self
::PARAM_MAX
],
1148 $paramSettings[self
::PARAM_MAX2
]
1154 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1158 if ( is_array( $value ) ) {
1159 foreach ( $value as $key => $val ) {
1160 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1163 $value = $this->validateTimestamp( $value, $encParamName );
1167 if ( is_array( $value ) ) {
1168 foreach ( $value as $key => $val ) {
1169 $value[$key] = $this->validateUser( $val, $encParamName );
1172 $value = $this->validateUser( $value, $encParamName );
1175 case 'upload': // nothing to do
1178 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1182 // Throw out duplicates if requested
1183 if ( !$dupes && is_array( $value ) ) {
1184 $value = array_unique( $value );
1187 // Set a warning if a deprecated parameter has been passed
1188 if ( $deprecated && $value !== false ) {
1189 $this->setWarning( "The $encParamName parameter has been deprecated." );
1191 } elseif ( $required ) {
1192 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1199 * Return an array of values that were given in a 'a|b|c' notation,
1200 * after it optionally validates them against the list allowed values.
1202 * @param string $valueName The name of the parameter (for error
1204 * @param mixed $value The value being parsed
1205 * @param bool $allowMultiple Can $value contain more than one value
1207 * @param mixed $allowedValues An array of values to check against. If
1208 * null, all values are accepted.
1209 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1211 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1212 if ( trim( $value ) === '' && $allowMultiple ) {
1216 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1217 // because it unstubs $wgUser
1218 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1219 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1223 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1224 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1225 "the limit is $sizeLimit" );
1228 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1229 // Bug 33482 - Allow entries with | in them for non-multiple values
1230 if ( in_array( $value, $allowedValues, true ) ) {
1234 $possibleValues = is_array( $allowedValues )
1235 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1238 "Only one $possibleValues is allowed for parameter '$valueName'",
1239 "multival_$valueName"
1243 if ( is_array( $allowedValues ) ) {
1244 // Check for unknown values
1245 $unknown = array_diff( $valuesList, $allowedValues );
1246 if ( count( $unknown ) ) {
1247 if ( $allowMultiple ) {
1248 $s = count( $unknown ) > 1 ?
's' : '';
1249 $vals = implode( ", ", $unknown );
1250 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1253 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1254 "unknown_$valueName"
1258 // Now throw them out
1259 $valuesList = array_intersect( $valuesList, $allowedValues );
1262 return $allowMultiple ?
$valuesList : $valuesList[0];
1266 * Validate the value against the minimum and user/bot maximum limits.
1267 * Prints usage info on failure.
1268 * @param string $paramName Parameter name
1269 * @param int $value Parameter value
1270 * @param int|null $min Minimum value
1271 * @param int|null $max Maximum value for users
1272 * @param int $botMax Maximum value for sysops/bots
1273 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1275 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1276 if ( !is_null( $min ) && $value < $min ) {
1278 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1279 $this->warnOrDie( $msg, $enforceLimits );
1283 // Minimum is always validated, whereas maximum is checked only if not
1284 // running in internal call mode
1285 if ( $this->getMain()->isInternalMode() ) {
1289 // Optimization: do not check user's bot status unless really needed -- skips db query
1290 // assumes $botMax >= $max
1291 if ( !is_null( $max ) && $value > $max ) {
1292 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1293 if ( $value > $botMax ) {
1294 $msg = $this->encodeParamName( $paramName ) .
1295 " may not be over $botMax (set to $value) for bots or sysops";
1296 $this->warnOrDie( $msg, $enforceLimits );
1300 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1301 $this->warnOrDie( $msg, $enforceLimits );
1308 * Validate and normalize of parameters of type 'timestamp'
1309 * @param string $value Parameter value
1310 * @param string $encParamName Parameter name
1311 * @return string Validated and normalized parameter
1313 function validateTimestamp( $value, $encParamName ) {
1314 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1315 if ( $unixTimestamp === false ) {
1317 "Invalid value '$value' for timestamp parameter $encParamName",
1318 "badtimestamp_{$encParamName}"
1322 return wfTimestamp( TS_MW
, $unixTimestamp );
1326 * Validate and normalize of parameters of type 'user'
1327 * @param string $value Parameter value
1328 * @param string $encParamName Parameter name
1329 * @return string Validated and normalized parameter
1331 private function validateUser( $value, $encParamName ) {
1332 $title = Title
::makeTitleSafe( NS_USER
, $value );
1333 if ( $title === null ) {
1335 "Invalid value '$value' for user parameter $encParamName",
1336 "baduser_{$encParamName}"
1340 return $title->getText();
1344 * Adds a warning to the output, else dies
1346 * @param string $msg Message to show as a warning, or error message if dying
1347 * @param bool $enforceLimits Whether this is an enforce (die)
1349 private function warnOrDie( $msg, $enforceLimits = false ) {
1350 if ( $enforceLimits ) {
1351 $this->dieUsage( $msg, 'integeroutofrange' );
1354 $this->setWarning( $msg );
1358 * Truncate an array to a certain length.
1359 * @param array $arr Array to truncate
1360 * @param int $limit Maximum length
1361 * @return bool True if the array was truncated, false otherwise
1363 public static function truncateArray( &$arr, $limit ) {
1365 while ( count( $arr ) > $limit ) {
1374 * Throw a UsageException, which will (if uncaught) call the main module's
1375 * error handler and die with an error message.
1377 * @param string $description One-line human-readable description of the
1378 * error condition, e.g., "The API requires a valid action parameter"
1379 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1380 * automated identification of the error, e.g., 'unknown_action'
1381 * @param int $httpRespCode HTTP response code
1382 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1383 * @throws UsageException
1385 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1386 Profiler
::instance()->close();
1387 throw new UsageException(
1389 $this->encodeParamName( $errorCode ),
1396 * Get error (as code, string) from a Status object.
1399 * @param Status $status
1400 * @return array Array of code and error string
1402 public function getErrorFromStatus( $status ) {
1403 if ( $status->isGood() ) {
1404 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1407 $errors = $status->getErrorsArray();
1409 // No errors? Assume the warnings should be treated as errors
1410 $errors = $status->getWarningsArray();
1413 // Still no errors? Punt
1414 $errors = array( array( 'unknownerror-nocode' ) );
1417 // Cannot use dieUsageMsg() because extensions might return custom
1419 if ( $errors[0] instanceof Message
) {
1421 $code = $msg->getKey();
1423 $code = array_shift( $errors[0] );
1424 $msg = wfMessage( $code, $errors[0] );
1426 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1427 // Translate message to code, for backwards compatability
1428 $code = ApiBase
::$messageMap[$code]['code'];
1431 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1435 * Throw a UsageException based on the errors in the Status object.
1438 * @param Status $status
1439 * @throws MWException
1441 public function dieStatus( $status ) {
1443 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1444 $this->dieUsage( $msg, $code );
1447 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1449 * Array that maps message keys to error messages. $1 and friends are replaced.
1451 public static $messageMap = array(
1452 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1453 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1454 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1456 // Messages from Title::getUserPermissionsErrors()
1457 'ns-specialprotected' => array(
1458 'code' => 'unsupportednamespace',
1459 'info' => "Pages in the Special namespace can't be edited"
1461 'protectedinterface' => array(
1462 'code' => 'protectednamespace-interface',
1463 'info' => "You're not allowed to edit interface messages"
1465 'namespaceprotected' => array(
1466 'code' => 'protectednamespace',
1467 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1469 'customcssprotected' => array(
1470 'code' => 'customcssprotected',
1471 'info' => "You're not allowed to edit custom CSS pages"
1473 'customjsprotected' => array(
1474 'code' => 'customjsprotected',
1475 'info' => "You're not allowed to edit custom JavaScript pages"
1477 'cascadeprotected' => array(
1478 'code' => 'cascadeprotected',
1479 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1481 'protectedpagetext' => array(
1482 'code' => 'protectedpage',
1483 'info' => "The \"\$1\" right is required to edit this page"
1485 'protect-cantedit' => array(
1486 'code' => 'cantedit',
1487 'info' => "You can't protect this page because you can't edit it"
1489 'badaccess-group0' => array(
1490 'code' => 'permissiondenied',
1491 'info' => "Permission denied"
1492 ), // Generic permission denied message
1493 'badaccess-groups' => array(
1494 'code' => 'permissiondenied',
1495 'info' => "Permission denied"
1497 'titleprotected' => array(
1498 'code' => 'protectedtitle',
1499 'info' => "This title has been protected from creation"
1501 'nocreate-loggedin' => array(
1502 'code' => 'cantcreate',
1503 'info' => "You don't have permission to create new pages"
1505 'nocreatetext' => array(
1506 'code' => 'cantcreate-anon',
1507 'info' => "Anonymous users can't create new pages"
1509 'movenologintext' => array(
1510 'code' => 'cantmove-anon',
1511 'info' => "Anonymous users can't move pages"
1513 'movenotallowed' => array(
1514 'code' => 'cantmove',
1515 'info' => "You don't have permission to move pages"
1517 'confirmedittext' => array(
1518 'code' => 'confirmemail',
1519 'info' => "You must confirm your email address before you can edit"
1521 'blockedtext' => array(
1522 'code' => 'blocked',
1523 'info' => "You have been blocked from editing"
1525 'autoblockedtext' => array(
1526 'code' => 'autoblocked',
1527 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1530 // Miscellaneous interface messages
1531 'actionthrottledtext' => array(
1532 'code' => 'ratelimited',
1533 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1535 'alreadyrolled' => array(
1536 'code' => 'alreadyrolled',
1537 'info' => "The page you tried to rollback was already rolled back"
1539 'cantrollback' => array(
1540 'code' => 'onlyauthor',
1541 'info' => "The page you tried to rollback only has one author"
1543 'readonlytext' => array(
1544 'code' => 'readonly',
1545 'info' => "The wiki is currently in read-only mode"
1547 'sessionfailure' => array(
1548 'code' => 'badtoken',
1549 'info' => "Invalid token" ),
1550 'cannotdelete' => array(
1551 'code' => 'cantdelete',
1552 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1554 'notanarticle' => array(
1555 'code' => 'missingtitle',
1556 'info' => "The page you requested doesn't exist"
1558 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1560 'immobile_namespace' => array(
1561 'code' => 'immobilenamespace',
1562 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1564 'articleexists' => array(
1565 'code' => 'articleexists',
1566 'info' => "The destination article already exists and is not a redirect to the source article"
1568 'protectedpage' => array(
1569 'code' => 'protectedpage',
1570 'info' => "You don't have permission to perform this move"
1572 'hookaborted' => array(
1573 'code' => 'hookaborted',
1574 'info' => "The modification you tried to make was aborted by an extension hook"
1576 'cantmove-titleprotected' => array(
1577 'code' => 'protectedtitle',
1578 'info' => "The destination article has been protected from creation"
1580 'imagenocrossnamespace' => array(
1581 'code' => 'nonfilenamespace',
1582 'info' => "Can't move a file to a non-file namespace"
1584 'imagetypemismatch' => array(
1585 'code' => 'filetypemismatch',
1586 'info' => "The new file extension doesn't match its type"
1588 // 'badarticleerror' => shouldn't happen
1589 // 'badtitletext' => shouldn't happen
1590 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1591 'range_block_disabled' => array(
1592 'code' => 'rangedisabled',
1593 'info' => "Blocking IP ranges has been disabled"
1595 'nosuchusershort' => array(
1596 'code' => 'nosuchuser',
1597 'info' => "The user you specified doesn't exist"
1599 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1600 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1601 'ipb_already_blocked' => array(
1602 'code' => 'alreadyblocked',
1603 'info' => "The user you tried to block was already blocked"
1605 'ipb_blocked_as_range' => array(
1606 'code' => 'blockedasrange',
1607 '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."
1609 'ipb_cant_unblock' => array(
1610 'code' => 'cantunblock',
1611 'info' => "The block you specified was not found. It may have been unblocked already"
1613 'mailnologin' => array(
1614 'code' => 'cantsend',
1615 '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"
1617 'ipbblocked' => array(
1618 'code' => 'ipbblocked',
1619 'info' => 'You cannot block or unblock users while you are yourself blocked'
1621 'ipbnounblockself' => array(
1622 'code' => 'ipbnounblockself',
1623 'info' => 'You are not allowed to unblock yourself'
1625 'usermaildisabled' => array(
1626 'code' => 'usermaildisabled',
1627 'info' => "User email has been disabled"
1629 'blockedemailuser' => array(
1630 'code' => 'blockedfrommail',
1631 'info' => "You have been blocked from sending email"
1633 'notarget' => array(
1634 'code' => 'notarget',
1635 'info' => "You have not specified a valid target for this action"
1638 'code' => 'noemail',
1639 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1641 'rcpatroldisabled' => array(
1642 'code' => 'patroldisabled',
1643 'info' => "Patrolling is disabled on this wiki"
1645 'markedaspatrollederror-noautopatrol' => array(
1646 'code' => 'noautopatrol',
1647 'info' => "You don't have permission to patrol your own changes"
1649 'delete-toobig' => array(
1650 'code' => 'bigdelete',
1651 'info' => "You can't delete this page because it has more than \$1 revisions"
1653 'movenotallowedfile' => array(
1654 'code' => 'cantmovefile',
1655 'info' => "You don't have permission to move files"
1657 'userrights-no-interwiki' => array(
1658 'code' => 'nointerwikiuserrights',
1659 'info' => "You don't have permission to change user rights on other wikis"
1661 'userrights-nodatabase' => array(
1662 'code' => 'nosuchdatabase',
1663 'info' => "Database \"\$1\" does not exist or is not local"
1665 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1666 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1667 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1668 'import-rootpage-invalid' => array(
1669 'code' => 'import-rootpage-invalid',
1670 'info' => 'Root page is an invalid title'
1672 'import-rootpage-nosubpage' => array(
1673 'code' => 'import-rootpage-nosubpage',
1674 'info' => 'Namespace "$1" of the root page does not allow subpages'
1677 // API-specific messages
1678 'readrequired' => array(
1679 'code' => 'readapidenied',
1680 'info' => "You need read permission to use this module"
1682 'writedisabled' => array(
1683 'code' => 'noapiwrite',
1684 '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"
1686 'writerequired' => array(
1687 'code' => 'writeapidenied',
1688 'info' => "You're not allowed to edit this wiki through the API"
1690 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1691 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1692 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1693 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1694 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1695 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1696 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1697 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1698 'create-titleexists' => array(
1699 'code' => 'create-titleexists',
1700 'info' => "Existing titles can't be protected with 'create'"
1702 'missingtitle-createonly' => array(
1703 'code' => 'missingtitle-createonly',
1704 'info' => "Missing titles can only be protected with 'create'"
1706 'cantblock' => array( 'code' => 'cantblock',
1707 'info' => "You don't have permission to block users"
1709 'canthide' => array(
1710 'code' => 'canthide',
1711 'info' => "You don't have permission to hide user names from the block log"
1713 'cantblock-email' => array(
1714 'code' => 'cantblock-email',
1715 'info' => "You don't have permission to block users from sending email through the wiki"
1717 'unblock-notarget' => array(
1718 'code' => 'notarget',
1719 'info' => "Either the id or the user parameter must be set"
1721 'unblock-idanduser' => array(
1722 'code' => 'idanduser',
1723 'info' => "The id and user parameters can't be used together"
1725 'cantunblock' => array(
1726 'code' => 'permissiondenied',
1727 'info' => "You don't have permission to unblock users"
1729 'cannotundelete' => array(
1730 'code' => 'cantundelete',
1731 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1733 'permdenied-undelete' => array(
1734 'code' => 'permissiondenied',
1735 'info' => "You don't have permission to restore deleted revisions"
1737 'createonly-exists' => array(
1738 'code' => 'articleexists',
1739 'info' => "The article you tried to create has been created already"
1741 'nocreate-missing' => array(
1742 'code' => 'missingtitle',
1743 'info' => "The article you tried to edit doesn't exist"
1745 'nosuchrcid' => array(
1746 'code' => 'nosuchrcid',
1747 'info' => "There is no change with rcid \"\$1\""
1749 'protect-invalidaction' => array(
1750 'code' => 'protect-invalidaction',
1751 'info' => "Invalid protection type \"\$1\""
1753 'protect-invalidlevel' => array(
1754 'code' => 'protect-invalidlevel',
1755 'info' => "Invalid protection level \"\$1\""
1757 'toofewexpiries' => array(
1758 'code' => 'toofewexpiries',
1759 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1761 'cantimport' => array(
1762 'code' => 'cantimport',
1763 'info' => "You don't have permission to import pages"
1765 'cantimport-upload' => array(
1766 'code' => 'cantimport-upload',
1767 'info' => "You don't have permission to import uploaded pages"
1769 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1770 'importuploaderrorsize' => array(
1771 'code' => 'filetoobig',
1772 'info' => 'The file you uploaded is bigger than the maximum upload size'
1774 'importuploaderrorpartial' => array(
1775 'code' => 'partialupload',
1776 'info' => 'The file was only partially uploaded'
1778 'importuploaderrortemp' => array(
1779 'code' => 'notempdir',
1780 'info' => 'The temporary upload directory is missing'
1782 'importcantopen' => array(
1783 'code' => 'cantopenfile',
1784 'info' => "Couldn't open the uploaded file"
1786 'import-noarticle' => array(
1787 'code' => 'badinterwiki',
1788 'info' => 'Invalid interwiki title specified'
1790 'importbadinterwiki' => array(
1791 'code' => 'badinterwiki',
1792 'info' => 'Invalid interwiki title specified'
1794 'import-unknownerror' => array(
1795 'code' => 'import-unknownerror',
1796 'info' => "Unknown error on import: \"\$1\""
1798 'cantoverwrite-sharedfile' => array(
1799 'code' => 'cantoverwrite-sharedfile',
1800 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1802 'sharedfile-exists' => array(
1803 'code' => 'fileexists-sharedrepo-perm',
1804 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1806 'mustbeposted' => array(
1807 'code' => 'mustbeposted',
1808 'info' => "The \$1 module requires a POST request"
1812 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1814 'specialpage-cantexecute' => array(
1815 'code' => 'specialpage-cantexecute',
1816 'info' => "You don't have permission to view the results of this special page"
1818 'invalidoldimage' => array(
1819 'code' => 'invalidoldimage',
1820 'info' => 'The oldimage parameter has invalid format'
1822 'nodeleteablefile' => array(
1823 'code' => 'nodeleteablefile',
1824 'info' => 'No such old version of the file'
1826 'fileexists-forbidden' => array(
1827 'code' => 'fileexists-forbidden',
1828 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1830 'fileexists-shared-forbidden' => array(
1831 'code' => 'fileexists-shared-forbidden',
1832 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1834 'filerevert-badversion' => array(
1835 'code' => 'filerevert-badversion',
1836 'info' => 'There is no previous local version of this file with the provided timestamp.'
1839 // ApiEditPage messages
1840 'noimageredirect-anon' => array(
1841 'code' => 'noimageredirect-anon',
1842 'info' => "Anonymous users can't create image redirects"
1844 'noimageredirect-logged' => array(
1845 'code' => 'noimageredirect',
1846 'info' => "You don't have permission to create image redirects"
1848 'spamdetected' => array(
1849 'code' => 'spamdetected',
1850 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1852 'contenttoobig' => array(
1853 'code' => 'contenttoobig',
1854 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1856 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1857 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1858 'wasdeleted' => array(
1859 'code' => 'pagedeleted',
1860 'info' => "The page has been deleted since you fetched its timestamp"
1862 'blankpage' => array(
1863 'code' => 'emptypage',
1864 'info' => "Creating new, empty pages is not allowed"
1866 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1867 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1868 'missingtext' => array(
1870 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1872 'emptynewsection' => array(
1873 'code' => 'emptynewsection',
1874 'info' => 'Creating empty new sections is not possible.'
1876 'revwrongpage' => array(
1877 'code' => 'revwrongpage',
1878 'info' => "r\$1 is not a revision of \"\$2\""
1880 'undo-failure' => array(
1881 'code' => 'undofailure',
1882 'info' => 'Undo failed due to conflicting intermediate edits'
1885 // Messages from WikiPage::doEit()
1886 'edit-hook-aborted' => array(
1887 'code' => 'edit-hook-aborted',
1888 'info' => "Your edit was aborted by an ArticleSave hook"
1890 'edit-gone-missing' => array(
1891 'code' => 'edit-gone-missing',
1892 'info' => "The page you tried to edit doesn't seem to exist anymore"
1894 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1895 'edit-already-exists' => array(
1896 'code' => 'edit-already-exists',
1897 'info' => 'It seems the page you tried to create already exist'
1901 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1902 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1903 'uploaddisabled' => array(
1904 'code' => 'uploaddisabled',
1905 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1907 'copyuploaddisabled' => array(
1908 'code' => 'copyuploaddisabled',
1909 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1911 'copyuploadbaddomain' => array(
1912 'code' => 'copyuploadbaddomain',
1913 'info' => 'Uploads by URL are not allowed from this domain.'
1915 'copyuploadbadurl' => array(
1916 'code' => 'copyuploadbadurl',
1917 'info' => 'Upload not allowed from this URL.'
1920 'filename-tooshort' => array(
1921 'code' => 'filename-tooshort',
1922 'info' => 'The filename is too short'
1924 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1925 'illegal-filename' => array(
1926 'code' => 'illegal-filename',
1927 'info' => 'The filename is not allowed'
1929 'filetype-missing' => array(
1930 'code' => 'filetype-missing',
1931 'info' => 'The file is missing an extension'
1934 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1936 // @codingStandardsIgnoreEnd
1939 * Helper function for readonly errors
1941 public function dieReadOnly() {
1942 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1943 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1944 array( 'readonlyreason' => wfReadOnlyReason() ) );
1948 * Output the error message related to a certain array
1949 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1951 public function dieUsageMsg( $error ) {
1952 # most of the time we send a 1 element, so we might as well send it as
1953 # a string and make this an array here.
1954 if ( is_string( $error ) ) {
1955 $error = array( $error );
1957 $parsed = $this->parseMsg( $error );
1958 $this->dieUsage( $parsed['info'], $parsed['code'] );
1962 * Will only set a warning instead of failing if the global $wgDebugAPI
1963 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1964 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1967 public function dieUsageMsgOrDebug( $error ) {
1969 if ( $wgDebugAPI !== true ) {
1970 $this->dieUsageMsg( $error );
1973 if ( is_string( $error ) ) {
1974 $error = array( $error );
1977 $parsed = $this->parseMsg( $error );
1978 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1982 * Die with the $prefix.'badcontinue' error. This call is common enough to
1983 * make it into the base method.
1984 * @param bool $condition Will only die if this value is true
1987 protected function dieContinueUsageIf( $condition ) {
1990 'Invalid continue param. You should pass the original value returned by the previous query',
1996 * Return the error message related to a certain array
1997 * @param array $error Element of a getUserPermissionsErrors()-style array
1998 * @return array('code' => code, 'info' => info)
2000 public function parseMsg( $error ) {
2001 $error = (array)$error; // It seems strings sometimes make their way in here
2002 $key = array_shift( $error );
2004 // Check whether the error array was nested
2005 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2006 if ( is_array( $key ) ) {
2008 $key = array_shift( $error );
2011 if ( isset( self
::$messageMap[$key] ) ) {
2013 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
2014 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2018 // If the key isn't present, throw an "unknown error"
2019 return $this->parseMsg( array( 'unknownerror', $key ) );
2023 * Internal code errors should be reported with this method
2024 * @param string $method Method or function name
2025 * @param string $message Error message
2026 * @throws MWException
2028 protected static function dieDebug( $method, $message ) {
2029 throw new MWException( "Internal error in $method: $message" );
2033 * Indicates if this module needs maxlag to be checked
2036 public function shouldCheckMaxlag() {
2041 * Indicates whether this module requires read rights
2044 public function isReadMode() {
2049 * Indicates whether this module requires write mode
2052 public function isWriteMode() {
2057 * Indicates whether this module must be called with a POST request
2060 public function mustBePosted() {
2065 * Returns whether this module requires a token to execute
2066 * It is used to show possible errors in action=paraminfo
2070 public function needsToken() {
2075 * Returns the token salt if there is one,
2076 * '' if the module doesn't require a salt,
2077 * else false if the module doesn't need a token
2078 * You have also to override needsToken()
2079 * Value is passed to User::getEditToken
2080 * @return bool|string|array
2082 public function getTokenSalt() {
2087 * Gets the user for whom to get the watchlist
2089 * @param array $params
2092 public function getWatchlistUser( $params ) {
2093 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2094 $user = User
::newFromName( $params['owner'], false );
2095 if ( !( $user && $user->getId() ) ) {
2096 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2098 $token = $user->getOption( 'watchlisttoken' );
2099 if ( $token == '' ||
$token != $params['token'] ) {
2101 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2106 if ( !$this->getUser()->isLoggedIn() ) {
2107 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2109 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2110 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2112 $user = $this->getUser();
2119 * @return bool|string|array Returns a false if the module has no help URL,
2120 * else returns a (array of) string
2122 public function getHelpUrls() {
2127 * Returns a list of all possible errors returned by the module
2129 * Don't call this function directly: use getFinalPossibleErrors() to allow
2130 * hooks to modify parameters as needed.
2132 * @return array Array in the format of array( key, param1, param2, ... )
2133 * or array( 'code' => ..., 'info' => ... )
2135 public function getPossibleErrors() {
2138 $params = $this->getFinalParams();
2140 foreach ( $params as $paramName => $paramSettings ) {
2141 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] )
2142 && $paramSettings[ApiBase
::PARAM_REQUIRED
]
2144 $ret[] = array( 'missingparam', $paramName );
2147 if ( array_key_exists( 'continue', $params ) ) {
2149 'code' => 'badcontinue',
2150 'info' => 'Invalid continue param. You should pass the ' .
2151 'original value returned by the previous query'
2156 if ( $this->mustBePosted() ) {
2157 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2160 if ( $this->isReadMode() ) {
2161 $ret[] = array( 'readrequired' );
2164 if ( $this->isWriteMode() ) {
2165 $ret[] = array( 'writerequired' );
2166 $ret[] = array( 'writedisabled' );
2169 if ( $this->needsToken() ) {
2170 if ( !isset( $params['token'][ApiBase
::PARAM_REQUIRED
] )
2171 ||
!$params['token'][ApiBase
::PARAM_REQUIRED
]
2173 // Add token as possible missing parameter, if not already done
2174 $ret[] = array( 'missingparam', 'token' );
2176 $ret[] = array( 'sessionfailure' );
2183 * Get final list of possible errors, after hooks have had a chance to
2184 * tweak it as needed.
2189 public function getFinalPossibleErrors() {
2190 $possibleErrors = $this->getPossibleErrors();
2191 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2193 return $possibleErrors;
2197 * Parses a list of errors into a standardised format
2198 * @param array $errors List of errors. Items can be in the for
2199 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2200 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2202 public function parseErrors( $errors ) {
2205 foreach ( $errors as $row ) {
2206 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2209 $ret[] = $this->parseMsg( $row );
2217 * Profiling: total module execution time
2219 private $mTimeIn = 0, $mModuleTime = 0;
2222 * Start module profiling
2224 public function profileIn() {
2225 if ( $this->mTimeIn
!== 0 ) {
2226 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2228 $this->mTimeIn
= microtime( true );
2229 wfProfileIn( $this->getModuleProfileName() );
2233 * End module profiling
2235 public function profileOut() {
2236 if ( $this->mTimeIn
=== 0 ) {
2237 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2239 if ( $this->mDBTimeIn
!== 0 ) {
2242 'Must be called after database profiling is done with profileDBOut()'
2246 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2248 wfProfileOut( $this->getModuleProfileName() );
2252 * When modules crash, sometimes it is needed to do a profileOut() regardless
2253 * of the profiling state the module was in. This method does such cleanup.
2255 public function safeProfileOut() {
2256 if ( $this->mTimeIn
!== 0 ) {
2257 if ( $this->mDBTimeIn
!== 0 ) {
2258 $this->profileDBOut();
2260 $this->profileOut();
2265 * Total time the module was executed
2268 public function getProfileTime() {
2269 if ( $this->mTimeIn
!== 0 ) {
2270 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2273 return $this->mModuleTime
;
2277 * Profiling: database execution time
2279 private $mDBTimeIn = 0, $mDBTime = 0;
2282 * Start module profiling
2284 public function profileDBIn() {
2285 if ( $this->mTimeIn
=== 0 ) {
2288 'Must be called while profiling the entire module with profileIn()'
2291 if ( $this->mDBTimeIn
!== 0 ) {
2292 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2294 $this->mDBTimeIn
= microtime( true );
2295 wfProfileIn( $this->getModuleProfileName( true ) );
2299 * End database profiling
2301 public function profileDBOut() {
2302 if ( $this->mTimeIn
=== 0 ) {
2303 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2304 'the entire module with profileIn()' );
2306 if ( $this->mDBTimeIn
=== 0 ) {
2307 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2310 $time = microtime( true ) - $this->mDBTimeIn
;
2311 $this->mDBTimeIn
= 0;
2313 $this->mDBTime +
= $time;
2314 $this->getMain()->mDBTime +
= $time;
2315 wfProfileOut( $this->getModuleProfileName( true ) );
2319 * Total time the module used the database
2322 public function getProfileDBTime() {
2323 if ( $this->mDBTimeIn
!== 0 ) {
2324 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2327 return $this->mDBTime
;
2331 * Gets a default slave database connection object
2332 * @return DatabaseBase
2334 protected function getDB() {
2335 if ( !isset( $this->mSlaveDB
) ) {
2336 $this->profileDBIn();
2337 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2338 $this->profileDBOut();
2341 return $this->mSlaveDB
;
2345 * Debugging function that prints a value and an optional backtrace
2346 * @param mixed $value Value to print
2347 * @param string $name Description of the printed value
2348 * @param bool $backtrace If true, print a backtrace
2350 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2351 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2352 var_export( $value );
2354 print "\n" . wfBacktrace();