5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI
= 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES
= 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED
= 7;
62 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE
= 9;
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT
= 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST
= 'LIST';
74 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE
= 1;
78 const LIMIT_BIG1
= 500; // Fast query, std user limit
79 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1
= 50; // Slow query, std user limit
81 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
88 const GET_VALUES_FOR_HELP
= 1;
93 private $mModuleName, $mModulePrefix;
94 private $mSlaveDB = null;
95 private $mParamCache = array();
98 * @param ApiMain $mainModule
99 * @param string $moduleName Name of this module
100 * @param string $modulePrefix Prefix to use for parameter names
102 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
103 $this->mMainModule
= $mainModule;
104 $this->mModuleName
= $moduleName;
105 $this->mModulePrefix
= $modulePrefix;
107 if ( !$this->isMain() ) {
108 $this->setContext( $mainModule->getContext() );
112 /*****************************************************************************
114 *****************************************************************************/
117 * Evaluates the parameters, performs the requested query, and sets up
118 * the result. Concrete implementations of ApiBase must override this
119 * method to provide whatever functionality their module offers.
120 * Implementations must not produce any output on their own and are not
121 * expected to handle any errors.
123 * The execute() method will be invoked directly by ApiMain immediately
124 * before the result of the module is output. Aside from the
125 * constructor, implementations should assume that no other methods
126 * will be called externally on the module before the result is
129 * The result data should be stored in the ApiResult object available
130 * through getResult().
132 abstract public function execute();
135 * Returns a string that identifies the version of the extending class.
136 * Typically includes the class name, the svn revision, timestamp, and
137 * last author. Usually done with SVN's Id keyword
139 * @deprecated since 1.21, version string is no longer supported
141 public function getVersion() {
142 wfDeprecated( __METHOD__
, '1.21' );
148 * Get the name of the module being executed by this instance
151 public function getModuleName() {
152 return $this->mModuleName
;
156 * Get the module manager, or null if this module has no sub-modules
158 * @return ApiModuleManager
160 public function getModuleManager() {
165 * Get parameter prefix (usually two letters or an empty string).
168 public function getModulePrefix() {
169 return $this->mModulePrefix
;
173 * Get the name of the module as shown in the profiler log
175 * @param DatabaseBase|bool $db
179 public function getModuleProfileName( $db = false ) {
181 return 'API:' . $this->mModuleName
. '-DB';
184 return 'API:' . $this->mModuleName
;
188 * Get the main module
191 public function getMain() {
192 return $this->mMainModule
;
196 * Returns true if this module is the main module ($this === $this->mMainModule),
200 public function isMain() {
201 return $this === $this->mMainModule
;
205 * Get the result object
208 public function getResult() {
209 // Main module has getResult() method overridden
210 // Safety - avoid infinite loop:
211 if ( $this->isMain() ) {
212 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
215 return $this->getMain()->getResult();
219 * Get the result data array (read-only)
222 public function getResultData() {
223 return $this->getResult()->getData();
227 * Set warning section for this module. Users should monitor this
228 * section to notice any changes in API. Multiple calls to this
229 * function will result in the warning messages being separated by
231 * @param string $warning Warning message
233 public function setWarning( $warning ) {
234 $result = $this->getResult();
235 $data = $result->getData();
236 $moduleName = $this->getModuleName();
237 if ( isset( $data['warnings'][$moduleName] ) ) {
238 // Don't add duplicate warnings
239 $oldWarning = $data['warnings'][$moduleName]['*'];
240 $warnPos = strpos( $oldWarning, $warning );
241 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
242 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
243 // Check if $warning is followed by "\n" or the end of the $oldWarning
244 $warnPos +
= strlen( $warning );
245 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
249 // If there is a warning already, append it to the existing one
250 $warning = "$oldWarning\n$warning";
253 ApiResult
::setContent( $msg, $warning );
254 $result->addValue( 'warnings', $moduleName,
255 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
259 * If the module may only be used with a certain format module,
260 * it should override this method to return an instance of that formatter.
261 * A value of null means the default format will be used.
262 * @return mixed Instance of a derived class of ApiFormatBase, or null
264 public function getCustomPrinter() {
269 * Generates help message for this module, or false if there is no description
270 * @return string|bool
272 public function makeHelpMsg() {
273 static $lnPrfx = "\n ";
275 $msg = $this->getFinalDescription();
277 if ( $msg !== false ) {
279 if ( !is_array( $msg ) ) {
284 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
286 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
288 if ( $this->isReadMode() ) {
289 $msg .= "\nThis module requires read rights";
291 if ( $this->isWriteMode() ) {
292 $msg .= "\nThis module requires write rights";
294 if ( $this->mustBePosted() ) {
295 $msg .= "\nThis module only accepts POST requests";
297 if ( $this->isReadMode() ||
$this->isWriteMode() ||
298 $this->mustBePosted()
304 $paramsMsg = $this->makeHelpMsgParameters();
305 if ( $paramsMsg !== false ) {
306 $msg .= "Parameters:\n$paramsMsg";
309 $examples = $this->getExamples();
311 if ( !is_array( $examples ) ) {
316 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
317 foreach ( $examples as $k => $v ) {
318 if ( is_numeric( $k ) ) {
321 if ( is_array( $v ) ) {
322 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
327 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
337 * @param string $item
340 private function indentExampleText( $item ) {
345 * @param string $prefix Text to split output items
346 * @param string $title What is being output
347 * @param string|array $input
350 protected function makeHelpArrayToString( $prefix, $title, $input ) {
351 if ( $input === false ) {
354 if ( !is_array( $input ) ) {
355 $input = array( $input );
358 if ( count( $input ) > 0 ) {
360 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
364 $msg .= implode( $prefix, $input ) . "\n";
373 * Generates the parameter descriptions for this module, to be displayed in the
375 * @return string|bool
377 public function makeHelpMsgParameters() {
378 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
381 $paramsDescription = $this->getFinalParamDescription();
383 $paramPrefix = "\n" . str_repeat( ' ', 24 );
384 $descWordwrap = "\n" . str_repeat( ' ', 28 );
385 foreach ( $params as $paramName => $paramSettings ) {
386 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
387 if ( is_array( $desc ) ) {
388 $desc = implode( $paramPrefix, $desc );
392 if ( !is_array( $paramSettings ) ) {
393 $paramSettings = array(
394 self
::PARAM_DFLT
=> $paramSettings,
398 //handle missing type
399 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
400 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
401 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
403 if ( is_bool( $dflt ) ) {
404 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
405 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
406 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
407 } elseif ( is_int( $dflt ) ) {
408 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
412 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
413 && $paramSettings[self
::PARAM_DEPRECATED
]
415 $desc = "DEPRECATED! $desc";
418 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
419 && $paramSettings[self
::PARAM_REQUIRED
]
421 $desc .= $paramPrefix . "This parameter is required";
424 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
425 ?
$paramSettings[self
::PARAM_TYPE
]
427 if ( isset( $type ) ) {
428 $hintPipeSeparated = true;
429 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
430 ?
$paramSettings[self
::PARAM_ISMULTI
]
433 $prompt = 'Values (separate with \'|\'): ';
435 $prompt = 'One value: ';
438 if ( is_array( $type ) ) {
441 foreach ( $type as $t ) {
443 $nothingPrompt = 'Can be empty, or ';
448 $desc .= $paramPrefix . $nothingPrompt . $prompt;
449 $choicesstring = implode( ', ', $choices );
450 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
451 $hintPipeSeparated = false;
455 // Special handling because namespaces are
456 // type-limited, yet they are not given
457 $desc .= $paramPrefix . $prompt;
458 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
459 100, $descWordwrap );
460 $hintPipeSeparated = false;
463 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
464 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
465 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
470 $s = $multi ?
's' : '';
471 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
472 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
473 if ( $hasMin ||
$hasMax ) {
475 $intRangeStr = "The value$s must be no less than " .
476 "{$paramSettings[self::PARAM_MIN]}";
477 } elseif ( !$hasMin ) {
478 $intRangeStr = "The value$s must be no more than " .
479 "{$paramSettings[self::PARAM_MAX]}";
481 $intRangeStr = "The value$s must be between " .
482 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
485 $desc .= $paramPrefix . $intRangeStr;
489 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
495 if ( $hintPipeSeparated ) {
496 $desc .= $paramPrefix . "Separate values with '|'";
499 $isArray = is_array( $type );
501 ||
$isArray && count( $type ) > self
::LIMIT_SML1
503 $desc .= $paramPrefix . "Maximum number of values " .
504 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
509 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
510 if ( !is_null( $default ) && $default !== false ) {
511 $desc .= $paramPrefix . "Default: $default";
514 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
524 * Returns the description string for this module
525 * @return string|array
527 protected function getDescription() {
532 * Returns usage examples for this module. Return false if no examples are available.
533 * @return bool|string|array
535 protected function getExamples() {
540 * Returns an array of allowed parameters (parameter name) => (default
541 * value) or (parameter name) => (array with PARAM_* constants as keys)
542 * Don't call this function directly: use getFinalParams() to allow
543 * hooks to modify parameters as needed.
545 * Some derived classes may choose to handle an integer $flags parameter
546 * in the overriding methods. Callers of this method can pass zero or
547 * more OR-ed flags like GET_VALUES_FOR_HELP.
551 protected function getAllowedParams( /* $flags = 0 */ ) {
552 // int $flags is not declared because it causes "Strict standards"
553 // warning. Most derived classes do not implement it.
558 * Returns an array of parameter descriptions.
559 * Don't call this function directly: use getFinalParamDescription() to
560 * allow hooks to modify descriptions as needed.
561 * @return array|bool False on no parameter descriptions
563 protected function getParamDescription() {
568 * Get final list of parameters, after hooks have had a chance to
569 * tweak it as needed.
571 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
572 * @return array|bool False on no parameters
573 * @since 1.21 $flags param added
575 public function getFinalParams( $flags = 0 ) {
576 $params = $this->getAllowedParams( $flags );
577 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
583 * Get final parameter descriptions, after hooks have had a chance to tweak it as
586 * @return array|bool False on no parameter descriptions
588 public function getFinalParamDescription() {
589 $desc = $this->getParamDescription();
590 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
596 * Returns possible properties in the result, grouped by the value of the prop parameter
599 * Properties that are shown always are in a group with empty string as a key.
600 * Properties that can be shown by several values of prop are included multiple times.
601 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
602 * those on the root object are under the key PROP_ROOT.
603 * The array can also contain a boolean under the key PROP_LIST,
604 * indicating whether the result is a list.
606 * Don't call this function directly: use getFinalResultProperties() to
607 * allow hooks to modify descriptions as needed.
609 * @return array|bool False on no properties
611 protected function getResultProperties() {
616 * Get final possible result properties, after hooks have had a chance to tweak it as
621 public function getFinalResultProperties() {
622 $properties = $this->getResultProperties();
623 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
629 * Add token properties to the array used by getResultProperties,
630 * based on a token functions mapping.
631 * @param array $props
632 * @param array $tokenFunctions
634 protected static function addTokenProperties( &$props, $tokenFunctions ) {
635 foreach ( array_keys( $tokenFunctions ) as $token ) {
636 $props[''][$token . 'token'] = array(
637 ApiBase
::PROP_TYPE
=> 'string',
638 ApiBase
::PROP_NULLABLE
=> true
644 * Get final module description, after hooks have had a chance to tweak it as
647 * @return array|bool False on no parameters
649 public function getFinalDescription() {
650 $desc = $this->getDescription();
651 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
657 * This method mangles parameter name based on the prefix supplied to the constructor.
658 * Override this method to change parameter name during runtime
659 * @param string $paramName Parameter name
660 * @return string Prefixed parameter name
662 public function encodeParamName( $paramName ) {
663 return $this->mModulePrefix
. $paramName;
667 * Using getAllowedParams(), this function makes an array of the values
668 * provided by the user, with key being the name of the variable, and
669 * value - validated value from user or default. limits will not be
670 * parsed if $parseLimit is set to false; use this when the max
671 * limit is not definitive yet, e.g. when getting revisions.
672 * @param bool $parseLimit True by default
675 public function extractRequestParams( $parseLimit = true ) {
676 // Cache parameters, for performance and to avoid bug 24564.
677 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
678 $params = $this->getFinalParams();
681 if ( $params ) { // getFinalParams() can return false
682 foreach ( $params as $paramName => $paramSettings ) {
683 $results[$paramName] = $this->getParameterFromSettings(
684 $paramName, $paramSettings, $parseLimit );
687 $this->mParamCache
[$parseLimit] = $results;
690 return $this->mParamCache
[$parseLimit];
694 * Get a value for the given parameter
695 * @param string $paramName Parameter name
696 * @param bool $parseLimit See extractRequestParams()
697 * @return mixed Parameter value
699 protected function getParameter( $paramName, $parseLimit = true ) {
700 $params = $this->getFinalParams();
701 $paramSettings = $params[$paramName];
703 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
707 * Die if none or more than one of a certain set of parameters is set and not false.
709 * Call getRequireOnlyOneParameterErrorMessages() to get a list of possible errors.
711 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
712 * @param string $required,... Names of parameters of which exactly one must be set
714 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
715 $required = func_get_args();
716 array_shift( $required );
717 $p = $this->getModulePrefix();
719 $intersection = array_intersect( array_keys( array_filter( $params,
720 array( $this, "parameterNotEmpty" ) ) ), $required );
722 if ( count( $intersection ) > 1 ) {
724 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
726 } elseif ( count( $intersection ) == 0 ) {
728 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
735 * Generates the possible errors requireOnlyOneParameter() can die with
737 * @param array $params
740 public function getRequireOnlyOneParameterErrorMessages( $params ) {
741 $p = $this->getModulePrefix();
742 $params = implode( ", {$p}", $params );
746 'code' => "{$p}missingparam",
747 'info' => "One of the parameters {$p}{$params} is required"
750 'code' => "{$p}invalidparammix",
751 'info' => "The parameters {$p}{$params} can not be used together"
757 * Die if more than one of a certain set of parameters is set and not false.
759 * Call getRequireMaxOneParameterErrorMessages() to get a list of possible errors.
761 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
762 * @param string $required,... Names of parameters of which at most one must be set
764 public function requireMaxOneParameter( $params, $required /*...*/ ) {
765 $required = func_get_args();
766 array_shift( $required );
767 $p = $this->getModulePrefix();
769 $intersection = array_intersect( array_keys( array_filter( $params,
770 array( $this, "parameterNotEmpty" ) ) ), $required );
772 if ( count( $intersection ) > 1 ) {
774 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
781 * Generates the possible error requireMaxOneParameter() can die with
783 * @param array $params
786 public function getRequireMaxOneParameterErrorMessages( $params ) {
787 $p = $this->getModulePrefix();
788 $params = implode( ", {$p}", $params );
792 'code' => "{$p}invalidparammix",
793 'info' => "The parameters {$p}{$params} can not be used together"
799 * Die if none of a certain set of parameters is set and not false.
801 * Call getRequireAtLeastOneParameterErrorMessages() to get a list of possible errors.
804 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
805 * @param string $required,... Names of parameters of which at least one must be set
807 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
808 $required = func_get_args();
809 array_shift( $required );
810 $p = $this->getModulePrefix();
812 $intersection = array_intersect(
813 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
817 if ( count( $intersection ) == 0 ) {
818 $this->dieUsage( "At least one of the parameters {$p}" .
819 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
824 * Generates the possible errors requireAtLeastOneParameter() can die with
827 * @param array $params Array of parameter key names
830 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
831 $p = $this->getModulePrefix();
832 $params = implode( ", {$p}", $params );
836 'code' => "{$p}missingparam",
837 'info' => "At least one of the parameters {$p}{$params} is required",
843 * Get a WikiPage object from a title or pageid param, if possible.
844 * Can die, if no param is set or if the title or page id is not valid.
846 * Call getTitleOrPageIdErrorMessage() to get a list of possible errors.
848 * @param array $params
849 * @param bool|string $load Whether load the object's state from the database:
850 * - false: don't load (if the pageid is given, it will still be loaded)
851 * - 'fromdb': load from a slave database
852 * - 'fromdbmaster': load from the master database
855 public function getTitleOrPageId( $params, $load = false ) {
856 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
859 if ( isset( $params['title'] ) ) {
860 $titleObj = Title
::newFromText( $params['title'] );
861 if ( !$titleObj ||
$titleObj->isExternal() ) {
862 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
864 if ( !$titleObj->canExist() ) {
865 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
867 $pageObj = WikiPage
::factory( $titleObj );
868 if ( $load !== false ) {
869 $pageObj->loadPageData( $load );
871 } elseif ( isset( $params['pageid'] ) ) {
872 if ( $load === false ) {
875 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
877 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
885 * Generates the possible error getTitleOrPageId() can die with
889 public function getTitleOrPageIdErrorMessage() {
891 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
893 array( 'invalidtitle', 'title' ),
894 array( 'nosuchpageid', 'pageid' ),
895 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
901 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
903 * @param object $x Parameter to check is not null/false
906 private function parameterNotEmpty( $x ) {
907 return !is_null( $x ) && $x !== false;
911 * Return true if we're to watch the page, false if not, null if no change.
912 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
913 * @param Title $titleObj The page under consideration
914 * @param string $userOption The user option to consider when $watchlist=preferences.
915 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
918 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
920 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
922 switch ( $watchlist ) {
930 # If the user is already watching, don't bother checking
931 if ( $userWatching ) {
934 # If no user option was passed, use watchdefault and watchcreations
935 if ( is_null( $userOption ) ) {
936 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
937 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
940 # Watch the article based on the user preference
941 return $this->getUser()->getBoolOption( $userOption );
944 return $userWatching;
947 return $userWatching;
952 * Set a watch (or unwatch) based the based on a watchlist parameter.
953 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
954 * @param Title $titleObj The article's title to change
955 * @param string $userOption The user option to consider when $watch=preferences
957 protected function setWatch( $watch, $titleObj, $userOption = null ) {
958 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
959 if ( $value === null ) {
963 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
967 * Using the settings determine the value for the given parameter
969 * @param string $paramName Parameter name
970 * @param array|mixed $paramSettings Default value or an array of settings
971 * using PARAM_* constants.
972 * @param bool $parseLimit Parse limit?
973 * @return mixed Parameter value
975 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
976 // Some classes may decide to change parameter names
977 $encParamName = $this->encodeParamName( $paramName );
979 if ( !is_array( $paramSettings ) ) {
980 $default = $paramSettings;
982 $type = gettype( $paramSettings );
987 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
988 ?
$paramSettings[self
::PARAM_DFLT
]
990 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
991 ?
$paramSettings[self
::PARAM_ISMULTI
]
993 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
994 ?
$paramSettings[self
::PARAM_TYPE
]
996 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
997 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
999 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1000 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1002 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1003 ?
$paramSettings[self
::PARAM_REQUIRED
]
1006 // When type is not given, and no choices, the type is the same as $default
1007 if ( !isset( $type ) ) {
1008 if ( isset( $default ) ) {
1009 $type = gettype( $default );
1011 $type = 'NULL'; // allow everything
1016 if ( $type == 'boolean' ) {
1017 if ( isset( $default ) && $default !== false ) {
1018 // Having a default value of anything other than 'false' is not allowed
1021 "Boolean param $encParamName's default is set to '$default'. " .
1022 "Boolean parameters must default to false."
1026 $value = $this->getMain()->getCheck( $encParamName );
1027 } elseif ( $type == 'upload' ) {
1028 if ( isset( $default ) ) {
1029 // Having a default value is not allowed
1032 "File upload param $encParamName's default is set to " .
1033 "'$default'. File upload parameters may not have a default." );
1036 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1038 $value = $this->getMain()->getUpload( $encParamName );
1039 if ( !$value->exists() ) {
1040 // This will get the value without trying to normalize it
1041 // (because trying to normalize a large binary file
1042 // accidentally uploaded as a field fails spectacularly)
1043 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1044 if ( $value !== null ) {
1046 "File upload param $encParamName is not a file upload; " .
1047 "be sure to use multipart/form-data for your POST and include " .
1048 "a filename in the Content-Disposition header.",
1049 "badupload_{$encParamName}"
1054 $value = $this->getMain()->getVal( $encParamName, $default );
1056 if ( isset( $value ) && $type == 'namespace' ) {
1057 $type = MWNamespace
::getValidNamespaces();
1061 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1062 $value = $this->parseMultiValue(
1066 is_array( $type ) ?
$type : null
1070 // More validation only when choices were not given
1071 // choices were validated in parseMultiValue()
1072 if ( isset( $value ) ) {
1073 if ( !is_array( $type ) ) {
1075 case 'NULL': // nothing to do
1078 if ( $required && $value === '' ) {
1079 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1082 case 'integer': // Force everything using intval() and optionally validate limits
1083 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1084 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1085 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1086 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1088 if ( is_array( $value ) ) {
1089 $value = array_map( 'intval', $value );
1090 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1091 foreach ( $value as &$v ) {
1092 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1096 $value = intval( $value );
1097 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1098 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1103 if ( !$parseLimit ) {
1104 // Don't do any validation whatsoever
1107 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1108 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1112 "MAX1 or MAX2 are not defined for the limit $encParamName"
1116 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1118 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1119 if ( $value == 'max' ) {
1120 $value = $this->getMain()->canApiHighLimits()
1121 ?
$paramSettings[self
::PARAM_MAX2
]
1122 : $paramSettings[self
::PARAM_MAX
];
1123 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1125 $value = intval( $value );
1126 $this->validateLimit(
1130 $paramSettings[self
::PARAM_MAX
],
1131 $paramSettings[self
::PARAM_MAX2
]
1137 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1141 if ( is_array( $value ) ) {
1142 foreach ( $value as $key => $val ) {
1143 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1146 $value = $this->validateTimestamp( $value, $encParamName );
1150 if ( is_array( $value ) ) {
1151 foreach ( $value as $key => $val ) {
1152 $value[$key] = $this->validateUser( $val, $encParamName );
1155 $value = $this->validateUser( $value, $encParamName );
1158 case 'upload': // nothing to do
1161 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1165 // Throw out duplicates if requested
1166 if ( !$dupes && is_array( $value ) ) {
1167 $value = array_unique( $value );
1170 // Set a warning if a deprecated parameter has been passed
1171 if ( $deprecated && $value !== false ) {
1172 $this->setWarning( "The $encParamName parameter has been deprecated." );
1174 } elseif ( $required ) {
1175 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1182 * Return an array of values that were given in a 'a|b|c' notation,
1183 * after it optionally validates them against the list allowed values.
1185 * @param string $valueName The name of the parameter (for error
1187 * @param mixed $value The value being parsed
1188 * @param bool $allowMultiple Can $value contain more than one value
1190 * @param string[]|null $allowedValues An array of values to check against. If
1191 * null, all values are accepted.
1192 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1194 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1195 if ( trim( $value ) === '' && $allowMultiple ) {
1199 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1200 // because it unstubs $wgUser
1201 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1202 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1206 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1207 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1208 "the limit is $sizeLimit" );
1211 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1212 // Bug 33482 - Allow entries with | in them for non-multiple values
1213 if ( in_array( $value, $allowedValues, true ) ) {
1217 $possibleValues = is_array( $allowedValues )
1218 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1221 "Only one $possibleValues is allowed for parameter '$valueName'",
1222 "multival_$valueName"
1226 if ( is_array( $allowedValues ) ) {
1227 // Check for unknown values
1228 $unknown = array_diff( $valuesList, $allowedValues );
1229 if ( count( $unknown ) ) {
1230 if ( $allowMultiple ) {
1231 $s = count( $unknown ) > 1 ?
's' : '';
1232 $vals = implode( ", ", $unknown );
1233 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1236 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1237 "unknown_$valueName"
1241 // Now throw them out
1242 $valuesList = array_intersect( $valuesList, $allowedValues );
1245 return $allowMultiple ?
$valuesList : $valuesList[0];
1249 * Validate the value against the minimum and user/bot maximum limits.
1250 * Prints usage info on failure.
1251 * @param string $paramName Parameter name
1252 * @param int $value Parameter value
1253 * @param int|null $min Minimum value
1254 * @param int|null $max Maximum value for users
1255 * @param int $botMax Maximum value for sysops/bots
1256 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1258 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1259 if ( !is_null( $min ) && $value < $min ) {
1261 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1262 $this->warnOrDie( $msg, $enforceLimits );
1266 // Minimum is always validated, whereas maximum is checked only if not
1267 // running in internal call mode
1268 if ( $this->getMain()->isInternalMode() ) {
1272 // Optimization: do not check user's bot status unless really needed -- skips db query
1273 // assumes $botMax >= $max
1274 if ( !is_null( $max ) && $value > $max ) {
1275 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1276 if ( $value > $botMax ) {
1277 $msg = $this->encodeParamName( $paramName ) .
1278 " may not be over $botMax (set to $value) for bots or sysops";
1279 $this->warnOrDie( $msg, $enforceLimits );
1283 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1284 $this->warnOrDie( $msg, $enforceLimits );
1291 * Validate and normalize of parameters of type 'timestamp'
1292 * @param string $value Parameter value
1293 * @param string $encParamName Parameter name
1294 * @return string Validated and normalized parameter
1296 function validateTimestamp( $value, $encParamName ) {
1297 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1298 if ( $unixTimestamp === false ) {
1300 "Invalid value '$value' for timestamp parameter $encParamName",
1301 "badtimestamp_{$encParamName}"
1305 return wfTimestamp( TS_MW
, $unixTimestamp );
1309 * Validate and normalize of parameters of type 'user'
1310 * @param string $value Parameter value
1311 * @param string $encParamName Parameter name
1312 * @return string Validated and normalized parameter
1314 private function validateUser( $value, $encParamName ) {
1315 $title = Title
::makeTitleSafe( NS_USER
, $value );
1316 if ( $title === null ) {
1318 "Invalid value '$value' for user parameter $encParamName",
1319 "baduser_{$encParamName}"
1323 return $title->getText();
1327 * Adds a warning to the output, else dies
1329 * @param string $msg Message to show as a warning, or error message if dying
1330 * @param bool $enforceLimits Whether this is an enforce (die)
1332 private function warnOrDie( $msg, $enforceLimits = false ) {
1333 if ( $enforceLimits ) {
1334 $this->dieUsage( $msg, 'integeroutofrange' );
1337 $this->setWarning( $msg );
1341 * Truncate an array to a certain length.
1342 * @param array $arr Array to truncate
1343 * @param int $limit Maximum length
1344 * @return bool True if the array was truncated, false otherwise
1346 public static function truncateArray( &$arr, $limit ) {
1348 while ( count( $arr ) > $limit ) {
1357 * Throw a UsageException, which will (if uncaught) call the main module's
1358 * error handler and die with an error message.
1360 * @param string $description One-line human-readable description of the
1361 * error condition, e.g., "The API requires a valid action parameter"
1362 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1363 * automated identification of the error, e.g., 'unknown_action'
1364 * @param int $httpRespCode HTTP response code
1365 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1366 * @throws UsageException
1368 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1369 Profiler
::instance()->close();
1370 throw new UsageException(
1372 $this->encodeParamName( $errorCode ),
1379 * Get error (as code, string) from a Status object.
1382 * @param Status $status
1383 * @return array Array of code and error string
1385 public function getErrorFromStatus( $status ) {
1386 if ( $status->isGood() ) {
1387 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1390 $errors = $status->getErrorsArray();
1392 // No errors? Assume the warnings should be treated as errors
1393 $errors = $status->getWarningsArray();
1396 // Still no errors? Punt
1397 $errors = array( array( 'unknownerror-nocode' ) );
1400 // Cannot use dieUsageMsg() because extensions might return custom
1402 if ( $errors[0] instanceof Message
) {
1404 $code = $msg->getKey();
1406 $code = array_shift( $errors[0] );
1407 $msg = wfMessage( $code, $errors[0] );
1409 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1410 // Translate message to code, for backwards compatability
1411 $code = ApiBase
::$messageMap[$code]['code'];
1414 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1418 * Throw a UsageException based on the errors in the Status object.
1421 * @param Status $status
1422 * @throws MWException
1424 public function dieStatus( $status ) {
1426 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1427 $this->dieUsage( $msg, $code );
1430 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1432 * Array that maps message keys to error messages. $1 and friends are replaced.
1434 public static $messageMap = array(
1435 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1436 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1437 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1439 // Messages from Title::getUserPermissionsErrors()
1440 'ns-specialprotected' => array(
1441 'code' => 'unsupportednamespace',
1442 'info' => "Pages in the Special namespace can't be edited"
1444 'protectedinterface' => array(
1445 'code' => 'protectednamespace-interface',
1446 'info' => "You're not allowed to edit interface messages"
1448 'namespaceprotected' => array(
1449 'code' => 'protectednamespace',
1450 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1452 'customcssprotected' => array(
1453 'code' => 'customcssprotected',
1454 'info' => "You're not allowed to edit custom CSS pages"
1456 'customjsprotected' => array(
1457 'code' => 'customjsprotected',
1458 'info' => "You're not allowed to edit custom JavaScript pages"
1460 'cascadeprotected' => array(
1461 'code' => 'cascadeprotected',
1462 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1464 'protectedpagetext' => array(
1465 'code' => 'protectedpage',
1466 'info' => "The \"\$1\" right is required to edit this page"
1468 'protect-cantedit' => array(
1469 'code' => 'cantedit',
1470 'info' => "You can't protect this page because you can't edit it"
1472 'badaccess-group0' => array(
1473 'code' => 'permissiondenied',
1474 'info' => "Permission denied"
1475 ), // Generic permission denied message
1476 'badaccess-groups' => array(
1477 'code' => 'permissiondenied',
1478 'info' => "Permission denied"
1480 'titleprotected' => array(
1481 'code' => 'protectedtitle',
1482 'info' => "This title has been protected from creation"
1484 'nocreate-loggedin' => array(
1485 'code' => 'cantcreate',
1486 'info' => "You don't have permission to create new pages"
1488 'nocreatetext' => array(
1489 'code' => 'cantcreate-anon',
1490 'info' => "Anonymous users can't create new pages"
1492 'movenologintext' => array(
1493 'code' => 'cantmove-anon',
1494 'info' => "Anonymous users can't move pages"
1496 'movenotallowed' => array(
1497 'code' => 'cantmove',
1498 'info' => "You don't have permission to move pages"
1500 'confirmedittext' => array(
1501 'code' => 'confirmemail',
1502 'info' => "You must confirm your email address before you can edit"
1504 'blockedtext' => array(
1505 'code' => 'blocked',
1506 'info' => "You have been blocked from editing"
1508 'autoblockedtext' => array(
1509 'code' => 'autoblocked',
1510 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1513 // Miscellaneous interface messages
1514 'actionthrottledtext' => array(
1515 'code' => 'ratelimited',
1516 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1518 'alreadyrolled' => array(
1519 'code' => 'alreadyrolled',
1520 'info' => "The page you tried to rollback was already rolled back"
1522 'cantrollback' => array(
1523 'code' => 'onlyauthor',
1524 'info' => "The page you tried to rollback only has one author"
1526 'readonlytext' => array(
1527 'code' => 'readonly',
1528 'info' => "The wiki is currently in read-only mode"
1530 'sessionfailure' => array(
1531 'code' => 'badtoken',
1532 'info' => "Invalid token" ),
1533 'cannotdelete' => array(
1534 'code' => 'cantdelete',
1535 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1537 'notanarticle' => array(
1538 'code' => 'missingtitle',
1539 'info' => "The page you requested doesn't exist"
1541 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1543 'immobile_namespace' => array(
1544 'code' => 'immobilenamespace',
1545 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1547 'articleexists' => array(
1548 'code' => 'articleexists',
1549 'info' => "The destination article already exists and is not a redirect to the source article"
1551 'protectedpage' => array(
1552 'code' => 'protectedpage',
1553 'info' => "You don't have permission to perform this move"
1555 'hookaborted' => array(
1556 'code' => 'hookaborted',
1557 'info' => "The modification you tried to make was aborted by an extension hook"
1559 'cantmove-titleprotected' => array(
1560 'code' => 'protectedtitle',
1561 'info' => "The destination article has been protected from creation"
1563 'imagenocrossnamespace' => array(
1564 'code' => 'nonfilenamespace',
1565 'info' => "Can't move a file to a non-file namespace"
1567 'imagetypemismatch' => array(
1568 'code' => 'filetypemismatch',
1569 'info' => "The new file extension doesn't match its type"
1571 // 'badarticleerror' => shouldn't happen
1572 // 'badtitletext' => shouldn't happen
1573 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1574 'range_block_disabled' => array(
1575 'code' => 'rangedisabled',
1576 'info' => "Blocking IP ranges has been disabled"
1578 'nosuchusershort' => array(
1579 'code' => 'nosuchuser',
1580 'info' => "The user you specified doesn't exist"
1582 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1583 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1584 'ipb_already_blocked' => array(
1585 'code' => 'alreadyblocked',
1586 'info' => "The user you tried to block was already blocked"
1588 'ipb_blocked_as_range' => array(
1589 'code' => 'blockedasrange',
1590 '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."
1592 'ipb_cant_unblock' => array(
1593 'code' => 'cantunblock',
1594 'info' => "The block you specified was not found. It may have been unblocked already"
1596 'mailnologin' => array(
1597 'code' => 'cantsend',
1598 '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"
1600 'ipbblocked' => array(
1601 'code' => 'ipbblocked',
1602 'info' => 'You cannot block or unblock users while you are yourself blocked'
1604 'ipbnounblockself' => array(
1605 'code' => 'ipbnounblockself',
1606 'info' => 'You are not allowed to unblock yourself'
1608 'usermaildisabled' => array(
1609 'code' => 'usermaildisabled',
1610 'info' => "User email has been disabled"
1612 'blockedemailuser' => array(
1613 'code' => 'blockedfrommail',
1614 'info' => "You have been blocked from sending email"
1616 'notarget' => array(
1617 'code' => 'notarget',
1618 'info' => "You have not specified a valid target for this action"
1621 'code' => 'noemail',
1622 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1624 'rcpatroldisabled' => array(
1625 'code' => 'patroldisabled',
1626 'info' => "Patrolling is disabled on this wiki"
1628 'markedaspatrollederror-noautopatrol' => array(
1629 'code' => 'noautopatrol',
1630 'info' => "You don't have permission to patrol your own changes"
1632 'delete-toobig' => array(
1633 'code' => 'bigdelete',
1634 'info' => "You can't delete this page because it has more than \$1 revisions"
1636 'movenotallowedfile' => array(
1637 'code' => 'cantmovefile',
1638 'info' => "You don't have permission to move files"
1640 'userrights-no-interwiki' => array(
1641 'code' => 'nointerwikiuserrights',
1642 'info' => "You don't have permission to change user rights on other wikis"
1644 'userrights-nodatabase' => array(
1645 'code' => 'nosuchdatabase',
1646 'info' => "Database \"\$1\" does not exist or is not local"
1648 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1649 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1650 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1651 'import-rootpage-invalid' => array(
1652 'code' => 'import-rootpage-invalid',
1653 'info' => 'Root page is an invalid title'
1655 'import-rootpage-nosubpage' => array(
1656 'code' => 'import-rootpage-nosubpage',
1657 'info' => 'Namespace "$1" of the root page does not allow subpages'
1660 // API-specific messages
1661 'readrequired' => array(
1662 'code' => 'readapidenied',
1663 'info' => "You need read permission to use this module"
1665 'writedisabled' => array(
1666 'code' => 'noapiwrite',
1667 '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"
1669 'writerequired' => array(
1670 'code' => 'writeapidenied',
1671 'info' => "You're not allowed to edit this wiki through the API"
1673 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1674 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1675 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1676 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1677 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1678 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1679 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1680 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1681 'create-titleexists' => array(
1682 'code' => 'create-titleexists',
1683 'info' => "Existing titles can't be protected with 'create'"
1685 'missingtitle-createonly' => array(
1686 'code' => 'missingtitle-createonly',
1687 'info' => "Missing titles can only be protected with 'create'"
1689 'cantblock' => array( 'code' => 'cantblock',
1690 'info' => "You don't have permission to block users"
1692 'canthide' => array(
1693 'code' => 'canthide',
1694 'info' => "You don't have permission to hide user names from the block log"
1696 'cantblock-email' => array(
1697 'code' => 'cantblock-email',
1698 'info' => "You don't have permission to block users from sending email through the wiki"
1700 'unblock-notarget' => array(
1701 'code' => 'notarget',
1702 'info' => "Either the id or the user parameter must be set"
1704 'unblock-idanduser' => array(
1705 'code' => 'idanduser',
1706 'info' => "The id and user parameters can't be used together"
1708 'cantunblock' => array(
1709 'code' => 'permissiondenied',
1710 'info' => "You don't have permission to unblock users"
1712 'cannotundelete' => array(
1713 'code' => 'cantundelete',
1714 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1716 'permdenied-undelete' => array(
1717 'code' => 'permissiondenied',
1718 'info' => "You don't have permission to restore deleted revisions"
1720 'createonly-exists' => array(
1721 'code' => 'articleexists',
1722 'info' => "The article you tried to create has been created already"
1724 'nocreate-missing' => array(
1725 'code' => 'missingtitle',
1726 'info' => "The article you tried to edit doesn't exist"
1728 'nosuchrcid' => array(
1729 'code' => 'nosuchrcid',
1730 'info' => "There is no change with rcid \"\$1\""
1732 'protect-invalidaction' => array(
1733 'code' => 'protect-invalidaction',
1734 'info' => "Invalid protection type \"\$1\""
1736 'protect-invalidlevel' => array(
1737 'code' => 'protect-invalidlevel',
1738 'info' => "Invalid protection level \"\$1\""
1740 'toofewexpiries' => array(
1741 'code' => 'toofewexpiries',
1742 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1744 'cantimport' => array(
1745 'code' => 'cantimport',
1746 'info' => "You don't have permission to import pages"
1748 'cantimport-upload' => array(
1749 'code' => 'cantimport-upload',
1750 'info' => "You don't have permission to import uploaded pages"
1752 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1753 'importuploaderrorsize' => array(
1754 'code' => 'filetoobig',
1755 'info' => 'The file you uploaded is bigger than the maximum upload size'
1757 'importuploaderrorpartial' => array(
1758 'code' => 'partialupload',
1759 'info' => 'The file was only partially uploaded'
1761 'importuploaderrortemp' => array(
1762 'code' => 'notempdir',
1763 'info' => 'The temporary upload directory is missing'
1765 'importcantopen' => array(
1766 'code' => 'cantopenfile',
1767 'info' => "Couldn't open the uploaded file"
1769 'import-noarticle' => array(
1770 'code' => 'badinterwiki',
1771 'info' => 'Invalid interwiki title specified'
1773 'importbadinterwiki' => array(
1774 'code' => 'badinterwiki',
1775 'info' => 'Invalid interwiki title specified'
1777 'import-unknownerror' => array(
1778 'code' => 'import-unknownerror',
1779 'info' => "Unknown error on import: \"\$1\""
1781 'cantoverwrite-sharedfile' => array(
1782 'code' => 'cantoverwrite-sharedfile',
1783 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1785 'sharedfile-exists' => array(
1786 'code' => 'fileexists-sharedrepo-perm',
1787 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1789 'mustbeposted' => array(
1790 'code' => 'mustbeposted',
1791 'info' => "The \$1 module requires a POST request"
1795 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1797 'specialpage-cantexecute' => array(
1798 'code' => 'specialpage-cantexecute',
1799 'info' => "You don't have permission to view the results of this special page"
1801 'invalidoldimage' => array(
1802 'code' => 'invalidoldimage',
1803 'info' => 'The oldimage parameter has invalid format'
1805 'nodeleteablefile' => array(
1806 'code' => 'nodeleteablefile',
1807 'info' => 'No such old version of the file'
1809 'fileexists-forbidden' => array(
1810 'code' => 'fileexists-forbidden',
1811 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1813 'fileexists-shared-forbidden' => array(
1814 'code' => 'fileexists-shared-forbidden',
1815 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1817 'filerevert-badversion' => array(
1818 'code' => 'filerevert-badversion',
1819 'info' => 'There is no previous local version of this file with the provided timestamp.'
1822 // ApiEditPage messages
1823 'noimageredirect-anon' => array(
1824 'code' => 'noimageredirect-anon',
1825 'info' => "Anonymous users can't create image redirects"
1827 'noimageredirect-logged' => array(
1828 'code' => 'noimageredirect',
1829 'info' => "You don't have permission to create image redirects"
1831 'spamdetected' => array(
1832 'code' => 'spamdetected',
1833 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1835 'contenttoobig' => array(
1836 'code' => 'contenttoobig',
1837 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1839 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1840 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1841 'wasdeleted' => array(
1842 'code' => 'pagedeleted',
1843 'info' => "The page has been deleted since you fetched its timestamp"
1845 'blankpage' => array(
1846 'code' => 'emptypage',
1847 'info' => "Creating new, empty pages is not allowed"
1849 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1850 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1851 'missingtext' => array(
1853 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1855 'emptynewsection' => array(
1856 'code' => 'emptynewsection',
1857 'info' => 'Creating empty new sections is not possible.'
1859 'revwrongpage' => array(
1860 'code' => 'revwrongpage',
1861 'info' => "r\$1 is not a revision of \"\$2\""
1863 'undo-failure' => array(
1864 'code' => 'undofailure',
1865 'info' => 'Undo failed due to conflicting intermediate edits'
1868 // Messages from WikiPage::doEit()
1869 'edit-hook-aborted' => array(
1870 'code' => 'edit-hook-aborted',
1871 'info' => "Your edit was aborted by an ArticleSave hook"
1873 'edit-gone-missing' => array(
1874 'code' => 'edit-gone-missing',
1875 'info' => "The page you tried to edit doesn't seem to exist anymore"
1877 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1878 'edit-already-exists' => array(
1879 'code' => 'edit-already-exists',
1880 'info' => 'It seems the page you tried to create already exist'
1884 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1885 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1886 'uploaddisabled' => array(
1887 'code' => 'uploaddisabled',
1888 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1890 'copyuploaddisabled' => array(
1891 'code' => 'copyuploaddisabled',
1892 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1894 'copyuploadbaddomain' => array(
1895 'code' => 'copyuploadbaddomain',
1896 'info' => 'Uploads by URL are not allowed from this domain.'
1898 'copyuploadbadurl' => array(
1899 'code' => 'copyuploadbadurl',
1900 'info' => 'Upload not allowed from this URL.'
1903 'filename-tooshort' => array(
1904 'code' => 'filename-tooshort',
1905 'info' => 'The filename is too short'
1907 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1908 'illegal-filename' => array(
1909 'code' => 'illegal-filename',
1910 'info' => 'The filename is not allowed'
1912 'filetype-missing' => array(
1913 'code' => 'filetype-missing',
1914 'info' => 'The file is missing an extension'
1917 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1919 // @codingStandardsIgnoreEnd
1922 * Helper function for readonly errors
1924 public function dieReadOnly() {
1925 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1926 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1927 array( 'readonlyreason' => wfReadOnlyReason() ) );
1931 * Output the error message related to a certain array
1932 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1934 public function dieUsageMsg( $error ) {
1935 # most of the time we send a 1 element, so we might as well send it as
1936 # a string and make this an array here.
1937 if ( is_string( $error ) ) {
1938 $error = array( $error );
1940 $parsed = $this->parseMsg( $error );
1941 $this->dieUsage( $parsed['info'], $parsed['code'] );
1945 * Will only set a warning instead of failing if the global $wgDebugAPI
1946 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1947 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1950 public function dieUsageMsgOrDebug( $error ) {
1951 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1952 $this->dieUsageMsg( $error );
1955 if ( is_string( $error ) ) {
1956 $error = array( $error );
1958 $parsed = $this->parseMsg( $error );
1959 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1963 * Die with the $prefix.'badcontinue' error. This call is common enough to
1964 * make it into the base method.
1965 * @param bool $condition Will only die if this value is true
1968 protected function dieContinueUsageIf( $condition ) {
1971 'Invalid continue param. You should pass the original value returned by the previous query',
1977 * Return the error message related to a certain array
1978 * @param array $error Element of a getUserPermissionsErrors()-style array
1979 * @return array('code' => code, 'info' => info)
1981 public function parseMsg( $error ) {
1982 $error = (array)$error; // It seems strings sometimes make their way in here
1983 $key = array_shift( $error );
1985 // Check whether the error array was nested
1986 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1987 if ( is_array( $key ) ) {
1989 $key = array_shift( $error );
1992 if ( isset( self
::$messageMap[$key] ) ) {
1994 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1995 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1999 // If the key isn't present, throw an "unknown error"
2000 return $this->parseMsg( array( 'unknownerror', $key ) );
2004 * Internal code errors should be reported with this method
2005 * @param string $method Method or function name
2006 * @param string $message Error message
2007 * @throws MWException
2009 protected static function dieDebug( $method, $message ) {
2010 throw new MWException( "Internal error in $method: $message" );
2014 * Indicates if this module needs maxlag to be checked
2017 public function shouldCheckMaxlag() {
2022 * Indicates whether this module requires read rights
2025 public function isReadMode() {
2030 * Indicates whether this module requires write mode
2033 public function isWriteMode() {
2038 * Indicates whether this module must be called with a POST request
2041 public function mustBePosted() {
2046 * Returns whether this module requires a token to execute
2047 * It is used to show possible errors in action=paraminfo
2051 public function needsToken() {
2056 * Returns the token salt if there is one,
2057 * '' if the module doesn't require a salt,
2058 * else false if the module doesn't need a token
2059 * You have also to override needsToken()
2060 * Value is passed to User::getEditToken
2061 * @return bool|string|array
2063 public function getTokenSalt() {
2068 * Gets the user for whom to get the watchlist
2070 * @param array $params
2073 public function getWatchlistUser( $params ) {
2074 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2075 $user = User
::newFromName( $params['owner'], false );
2076 if ( !( $user && $user->getId() ) ) {
2077 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2079 $token = $user->getOption( 'watchlisttoken' );
2080 if ( $token == '' ||
$token != $params['token'] ) {
2082 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2087 if ( !$this->getUser()->isLoggedIn() ) {
2088 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2090 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2091 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2093 $user = $this->getUser();
2100 * @return bool|string|array Returns a false if the module has no help URL,
2101 * else returns a (array of) string
2103 public function getHelpUrls() {
2108 * Returns a list of all possible errors returned by the module
2110 * Don't call this function directly: use getFinalPossibleErrors() to allow
2111 * hooks to modify parameters as needed.
2113 * @return array Array in the format of array( key, param1, param2, ... )
2114 * or array( 'code' => ..., 'info' => ... )
2116 public function getPossibleErrors() {
2119 $params = $this->getFinalParams();
2121 foreach ( $params as $paramName => $paramSettings ) {
2122 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] )
2123 && $paramSettings[ApiBase
::PARAM_REQUIRED
]
2125 $ret[] = array( 'missingparam', $paramName );
2128 if ( array_key_exists( 'continue', $params ) ) {
2130 'code' => 'badcontinue',
2131 'info' => 'Invalid continue param. You should pass the ' .
2132 'original value returned by the previous query'
2137 if ( $this->mustBePosted() ) {
2138 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2141 if ( $this->isReadMode() ) {
2142 $ret[] = array( 'readrequired' );
2145 if ( $this->isWriteMode() ) {
2146 $ret[] = array( 'writerequired' );
2147 $ret[] = array( 'writedisabled' );
2150 if ( $this->needsToken() ) {
2151 if ( !isset( $params['token'][ApiBase
::PARAM_REQUIRED
] )
2152 ||
!$params['token'][ApiBase
::PARAM_REQUIRED
]
2154 // Add token as possible missing parameter, if not already done
2155 $ret[] = array( 'missingparam', 'token' );
2157 $ret[] = array( 'sessionfailure' );
2164 * Get final list of possible errors, after hooks have had a chance to
2165 * tweak it as needed.
2170 public function getFinalPossibleErrors() {
2171 $possibleErrors = $this->getPossibleErrors();
2172 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2174 return $possibleErrors;
2178 * Parses a list of errors into a standardised format
2179 * @param array $errors List of errors. Items can be in the for
2180 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2181 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2183 public function parseErrors( $errors ) {
2186 foreach ( $errors as $row ) {
2187 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2190 $ret[] = $this->parseMsg( $row );
2198 * Profiling: total module execution time
2200 private $mTimeIn = 0, $mModuleTime = 0;
2203 * Start module profiling
2205 public function profileIn() {
2206 if ( $this->mTimeIn
!== 0 ) {
2207 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2209 $this->mTimeIn
= microtime( true );
2210 wfProfileIn( $this->getModuleProfileName() );
2214 * End module profiling
2216 public function profileOut() {
2217 if ( $this->mTimeIn
=== 0 ) {
2218 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2220 if ( $this->mDBTimeIn
!== 0 ) {
2223 'Must be called after database profiling is done with profileDBOut()'
2227 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2229 wfProfileOut( $this->getModuleProfileName() );
2233 * When modules crash, sometimes it is needed to do a profileOut() regardless
2234 * of the profiling state the module was in. This method does such cleanup.
2236 public function safeProfileOut() {
2237 if ( $this->mTimeIn
!== 0 ) {
2238 if ( $this->mDBTimeIn
!== 0 ) {
2239 $this->profileDBOut();
2241 $this->profileOut();
2246 * Total time the module was executed
2249 public function getProfileTime() {
2250 if ( $this->mTimeIn
!== 0 ) {
2251 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2254 return $this->mModuleTime
;
2258 * Profiling: database execution time
2260 private $mDBTimeIn = 0, $mDBTime = 0;
2263 * Start module profiling
2265 public function profileDBIn() {
2266 if ( $this->mTimeIn
=== 0 ) {
2269 'Must be called while profiling the entire module with profileIn()'
2272 if ( $this->mDBTimeIn
!== 0 ) {
2273 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2275 $this->mDBTimeIn
= microtime( true );
2276 wfProfileIn( $this->getModuleProfileName( true ) );
2280 * End database profiling
2282 public function profileDBOut() {
2283 if ( $this->mTimeIn
=== 0 ) {
2284 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2285 'the entire module with profileIn()' );
2287 if ( $this->mDBTimeIn
=== 0 ) {
2288 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2291 $time = microtime( true ) - $this->mDBTimeIn
;
2292 $this->mDBTimeIn
= 0;
2294 $this->mDBTime +
= $time;
2295 $this->getMain()->mDBTime +
= $time;
2296 wfProfileOut( $this->getModuleProfileName( true ) );
2300 * Total time the module used the database
2303 public function getProfileDBTime() {
2304 if ( $this->mDBTimeIn
!== 0 ) {
2305 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2308 return $this->mDBTime
;
2312 * Gets a default slave database connection object
2313 * @return DatabaseBase
2315 protected function getDB() {
2316 if ( !isset( $this->mSlaveDB
) ) {
2317 $this->profileDBIn();
2318 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2319 $this->profileDBOut();
2322 return $this->mSlaveDB
;
2326 * Debugging function that prints a value and an optional backtrace
2327 * @param mixed $value Value to print
2328 * @param string $name Description of the printed value
2329 * @param bool $backtrace If true, print a backtrace
2331 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2332 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2333 var_export( $value );
2335 print "\n" . wfBacktrace();