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->disableSizeCheck();
255 $result->addValue( 'warnings', $moduleName,
256 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
257 $result->enableSizeCheck();
261 * If the module may only be used with a certain format module,
262 * it should override this method to return an instance of that formatter.
263 * A value of null means the default format will be used.
264 * @return mixed Instance of a derived class of ApiFormatBase, or null
266 public function getCustomPrinter() {
271 * Generates help message for this module, or false if there is no description
272 * @return string|bool
274 public function makeHelpMsg() {
275 static $lnPrfx = "\n ";
277 $msg = $this->getFinalDescription();
279 if ( $msg !== false ) {
281 if ( !is_array( $msg ) ) {
286 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
288 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
290 if ( $this->isReadMode() ) {
291 $msg .= "\nThis module requires read rights";
293 if ( $this->isWriteMode() ) {
294 $msg .= "\nThis module requires write rights";
296 if ( $this->mustBePosted() ) {
297 $msg .= "\nThis module only accepts POST requests";
299 if ( $this->isReadMode() ||
$this->isWriteMode() ||
300 $this->mustBePosted()
306 $paramsMsg = $this->makeHelpMsgParameters();
307 if ( $paramsMsg !== false ) {
308 $msg .= "Parameters:\n$paramsMsg";
311 $examples = $this->getExamples();
313 if ( !is_array( $examples ) ) {
318 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
319 foreach ( $examples as $k => $v ) {
320 if ( is_numeric( $k ) ) {
323 if ( is_array( $v ) ) {
324 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
329 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
339 * @param string $item
342 private function indentExampleText( $item ) {
347 * @param string $prefix Text to split output items
348 * @param string $title What is being output
349 * @param string|array $input
352 protected function makeHelpArrayToString( $prefix, $title, $input ) {
353 if ( $input === false ) {
356 if ( !is_array( $input ) ) {
357 $input = array( $input );
360 if ( count( $input ) > 0 ) {
362 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
366 $msg .= implode( $prefix, $input ) . "\n";
375 * Generates the parameter descriptions for this module, to be displayed in the
377 * @return string|bool
379 public function makeHelpMsgParameters() {
380 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
383 $paramsDescription = $this->getFinalParamDescription();
385 $paramPrefix = "\n" . str_repeat( ' ', 24 );
386 $descWordwrap = "\n" . str_repeat( ' ', 28 );
387 foreach ( $params as $paramName => $paramSettings ) {
388 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
389 if ( is_array( $desc ) ) {
390 $desc = implode( $paramPrefix, $desc );
394 if ( !is_array( $paramSettings ) ) {
395 $paramSettings = array(
396 self
::PARAM_DFLT
=> $paramSettings,
400 //handle missing type
401 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
402 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] )
403 ?
$paramSettings[ApiBase
::PARAM_DFLT
]
405 if ( is_bool( $dflt ) ) {
406 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
407 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
408 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
409 } elseif ( is_int( $dflt ) ) {
410 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
414 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] )
415 && $paramSettings[self
::PARAM_DEPRECATED
]
417 $desc = "DEPRECATED! $desc";
420 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] )
421 && $paramSettings[self
::PARAM_REQUIRED
]
423 $desc .= $paramPrefix . "This parameter is required";
426 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
427 ?
$paramSettings[self
::PARAM_TYPE
]
429 if ( isset( $type ) ) {
430 $hintPipeSeparated = true;
431 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
432 ?
$paramSettings[self
::PARAM_ISMULTI
]
435 $prompt = 'Values (separate with \'|\'): ';
437 $prompt = 'One value: ';
440 if ( is_array( $type ) ) {
443 foreach ( $type as $t ) {
445 $nothingPrompt = 'Can be empty, or ';
450 $desc .= $paramPrefix . $nothingPrompt . $prompt;
451 $choicesstring = implode( ', ', $choices );
452 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
453 $hintPipeSeparated = false;
457 // Special handling because namespaces are
458 // type-limited, yet they are not given
459 $desc .= $paramPrefix . $prompt;
460 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
461 100, $descWordwrap );
462 $hintPipeSeparated = false;
465 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
466 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
467 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
472 $s = $multi ?
's' : '';
473 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
474 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
475 if ( $hasMin ||
$hasMax ) {
477 $intRangeStr = "The value$s must be no less than " .
478 "{$paramSettings[self::PARAM_MIN]}";
479 } elseif ( !$hasMin ) {
480 $intRangeStr = "The value$s must be no more than " .
481 "{$paramSettings[self::PARAM_MAX]}";
483 $intRangeStr = "The value$s must be between " .
484 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
487 $desc .= $paramPrefix . $intRangeStr;
491 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
497 if ( $hintPipeSeparated ) {
498 $desc .= $paramPrefix . "Separate values with '|'";
501 $isArray = is_array( $type );
503 ||
$isArray && count( $type ) > self
::LIMIT_SML1
505 $desc .= $paramPrefix . "Maximum number of values " .
506 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
511 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
512 if ( !is_null( $default ) && $default !== false ) {
513 $desc .= $paramPrefix . "Default: $default";
516 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
526 * Returns the description string for this module
527 * @return string|array
529 protected function getDescription() {
534 * Returns usage examples for this module. Return false if no examples are available.
535 * @return bool|string|array
537 protected function getExamples() {
542 * Returns an array of allowed parameters (parameter name) => (default
543 * value) or (parameter name) => (array with PARAM_* constants as keys)
544 * Don't call this function directly: use getFinalParams() to allow
545 * hooks to modify parameters as needed.
547 * Some derived classes may choose to handle an integer $flags parameter
548 * in the overriding methods. Callers of this method can pass zero or
549 * more OR-ed flags like GET_VALUES_FOR_HELP.
553 protected function getAllowedParams( /* $flags = 0 */ ) {
554 // int $flags is not declared because it causes "Strict standards"
555 // warning. Most derived classes do not implement it.
560 * Returns an array of parameter descriptions.
561 * Don't call this function directly: use getFinalParamDescription() to
562 * allow hooks to modify descriptions as needed.
563 * @return array|bool False on no parameter descriptions
565 protected function getParamDescription() {
570 * Get final list of parameters, after hooks have had a chance to
571 * tweak it as needed.
573 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
574 * @return array|bool False on no parameters
575 * @since 1.21 $flags param added
577 public function getFinalParams( $flags = 0 ) {
578 $params = $this->getAllowedParams( $flags );
579 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
585 * Get final parameter descriptions, after hooks have had a chance to tweak it as
588 * @return array|bool False on no parameter descriptions
590 public function getFinalParamDescription() {
591 $desc = $this->getParamDescription();
592 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
598 * Returns possible properties in the result, grouped by the value of the prop parameter
601 * Properties that are shown always are in a group with empty string as a key.
602 * Properties that can be shown by several values of prop are included multiple times.
603 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
604 * those on the root object are under the key PROP_ROOT.
605 * The array can also contain a boolean under the key PROP_LIST,
606 * indicating whether the result is a list.
608 * Don't call this function directly: use getFinalResultProperties() to
609 * allow hooks to modify descriptions as needed.
611 * @return array|bool False on no properties
613 protected function getResultProperties() {
618 * Get final possible result properties, after hooks have had a chance to tweak it as
623 public function getFinalResultProperties() {
624 $properties = $this->getResultProperties();
625 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
631 * Add token properties to the array used by getResultProperties,
632 * based on a token functions mapping.
633 * @param array $props
634 * @param array $tokenFunctions
636 protected static function addTokenProperties( &$props, $tokenFunctions ) {
637 foreach ( array_keys( $tokenFunctions ) as $token ) {
638 $props[''][$token . 'token'] = array(
639 ApiBase
::PROP_TYPE
=> 'string',
640 ApiBase
::PROP_NULLABLE
=> true
646 * Get final module description, after hooks have had a chance to tweak it as
649 * @return array|bool False on no parameters
651 public function getFinalDescription() {
652 $desc = $this->getDescription();
653 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
659 * This method mangles parameter name based on the prefix supplied to the constructor.
660 * Override this method to change parameter name during runtime
661 * @param string $paramName Parameter name
662 * @return string Prefixed parameter name
664 public function encodeParamName( $paramName ) {
665 return $this->mModulePrefix
. $paramName;
669 * Using getAllowedParams(), this function makes an array of the values
670 * provided by the user, with key being the name of the variable, and
671 * value - validated value from user or default. limits will not be
672 * parsed if $parseLimit is set to false; use this when the max
673 * limit is not definitive yet, e.g. when getting revisions.
674 * @param bool $parseLimit True by default
677 public function extractRequestParams( $parseLimit = true ) {
678 // Cache parameters, for performance and to avoid bug 24564.
679 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
680 $params = $this->getFinalParams();
683 if ( $params ) { // getFinalParams() can return false
684 foreach ( $params as $paramName => $paramSettings ) {
685 $results[$paramName] = $this->getParameterFromSettings(
686 $paramName, $paramSettings, $parseLimit );
689 $this->mParamCache
[$parseLimit] = $results;
692 return $this->mParamCache
[$parseLimit];
696 * Get a value for the given parameter
697 * @param string $paramName Parameter name
698 * @param bool $parseLimit See extractRequestParams()
699 * @return mixed Parameter value
701 protected function getParameter( $paramName, $parseLimit = true ) {
702 $params = $this->getFinalParams();
703 $paramSettings = $params[$paramName];
705 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
709 * Die if none or more than one of a certain set of parameters is set and not false.
711 * Call getRequireOnlyOneParameterErrorMessages() to get a list of possible errors.
713 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
714 * @param string $required,... Names of parameters of which exactly one must be set
716 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
717 $required = func_get_args();
718 array_shift( $required );
719 $p = $this->getModulePrefix();
721 $intersection = array_intersect( array_keys( array_filter( $params,
722 array( $this, "parameterNotEmpty" ) ) ), $required );
724 if ( count( $intersection ) > 1 ) {
726 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
728 } elseif ( count( $intersection ) == 0 ) {
730 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
737 * Generates the possible errors requireOnlyOneParameter() can die with
739 * @param array $params
742 public function getRequireOnlyOneParameterErrorMessages( $params ) {
743 $p = $this->getModulePrefix();
744 $params = implode( ", {$p}", $params );
748 'code' => "{$p}missingparam",
749 'info' => "One of the parameters {$p}{$params} is required"
752 'code' => "{$p}invalidparammix",
753 'info' => "The parameters {$p}{$params} can not be used together"
759 * Die if more than one of a certain set of parameters is set and not false.
761 * Call getRequireMaxOneParameterErrorMessages() to get a list of possible errors.
763 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
764 * @param string $required,... Names of parameters of which at most one must be set
766 public function requireMaxOneParameter( $params, $required /*...*/ ) {
767 $required = func_get_args();
768 array_shift( $required );
769 $p = $this->getModulePrefix();
771 $intersection = array_intersect( array_keys( array_filter( $params,
772 array( $this, "parameterNotEmpty" ) ) ), $required );
774 if ( count( $intersection ) > 1 ) {
776 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
783 * Generates the possible error requireMaxOneParameter() can die with
785 * @param array $params
788 public function getRequireMaxOneParameterErrorMessages( $params ) {
789 $p = $this->getModulePrefix();
790 $params = implode( ", {$p}", $params );
794 'code' => "{$p}invalidparammix",
795 'info' => "The parameters {$p}{$params} can not be used together"
801 * Die if none of a certain set of parameters is set and not false.
803 * Call getRequireAtLeastOneParameterErrorMessages() to get a list of possible errors.
806 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
807 * @param string $required,... Names of parameters of which at least one must be set
809 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
810 $required = func_get_args();
811 array_shift( $required );
812 $p = $this->getModulePrefix();
814 $intersection = array_intersect(
815 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
819 if ( count( $intersection ) == 0 ) {
820 $this->dieUsage( "At least one of the parameters {$p}" .
821 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
826 * Generates the possible errors requireAtLeastOneParameter() can die with
829 * @param array $params Array of parameter key names
832 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
833 $p = $this->getModulePrefix();
834 $params = implode( ", {$p}", $params );
838 'code' => "{$p}missingparam",
839 'info' => "At least one of the parameters {$p}{$params} is required",
845 * Get a WikiPage object from a title or pageid param, if possible.
846 * Can die, if no param is set or if the title or page id is not valid.
848 * Call getTitleOrPageIdErrorMessage() to get a list of possible errors.
850 * @param array $params
851 * @param bool|string $load Whether load the object's state from the database:
852 * - false: don't load (if the pageid is given, it will still be loaded)
853 * - 'fromdb': load from a slave database
854 * - 'fromdbmaster': load from the master database
857 public function getTitleOrPageId( $params, $load = false ) {
858 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
861 if ( isset( $params['title'] ) ) {
862 $titleObj = Title
::newFromText( $params['title'] );
863 if ( !$titleObj ||
$titleObj->isExternal() ) {
864 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
866 if ( !$titleObj->canExist() ) {
867 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
869 $pageObj = WikiPage
::factory( $titleObj );
870 if ( $load !== false ) {
871 $pageObj->loadPageData( $load );
873 } elseif ( isset( $params['pageid'] ) ) {
874 if ( $load === false ) {
877 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
879 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
887 * Generates the possible error getTitleOrPageId() can die with
891 public function getTitleOrPageIdErrorMessage() {
893 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
895 array( 'invalidtitle', 'title' ),
896 array( 'nosuchpageid', 'pageid' ),
897 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
903 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
905 * @param object $x Parameter to check is not null/false
908 private function parameterNotEmpty( $x ) {
909 return !is_null( $x ) && $x !== false;
913 * Return true if we're to watch the page, false if not, null if no change.
914 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
915 * @param Title $titleObj The page under consideration
916 * @param string $userOption The user option to consider when $watchlist=preferences.
917 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
920 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
922 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem
::IGNORE_USER_RIGHTS
);
924 switch ( $watchlist ) {
932 # If the user is already watching, don't bother checking
933 if ( $userWatching ) {
936 # If no user option was passed, use watchdefault and watchcreations
937 if ( is_null( $userOption ) ) {
938 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
939 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
942 # Watch the article based on the user preference
943 return $this->getUser()->getBoolOption( $userOption );
946 return $userWatching;
949 return $userWatching;
954 * Set a watch (or unwatch) based the based on a watchlist parameter.
955 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
956 * @param Title $titleObj The article's title to change
957 * @param string $userOption The user option to consider when $watch=preferences
959 protected function setWatch( $watch, $titleObj, $userOption = null ) {
960 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
961 if ( $value === null ) {
965 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
969 * Using the settings determine the value for the given parameter
971 * @param string $paramName Parameter name
972 * @param array|mixed $paramSettings Default value or an array of settings
973 * using PARAM_* constants.
974 * @param bool $parseLimit Parse limit?
975 * @return mixed Parameter value
977 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
978 // Some classes may decide to change parameter names
979 $encParamName = $this->encodeParamName( $paramName );
981 if ( !is_array( $paramSettings ) ) {
982 $default = $paramSettings;
984 $type = gettype( $paramSettings );
989 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
990 ?
$paramSettings[self
::PARAM_DFLT
]
992 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
993 ?
$paramSettings[self
::PARAM_ISMULTI
]
995 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
996 ?
$paramSettings[self
::PARAM_TYPE
]
998 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
999 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1001 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1002 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1004 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1005 ?
$paramSettings[self
::PARAM_REQUIRED
]
1008 // When type is not given, and no choices, the type is the same as $default
1009 if ( !isset( $type ) ) {
1010 if ( isset( $default ) ) {
1011 $type = gettype( $default );
1013 $type = 'NULL'; // allow everything
1018 if ( $type == 'boolean' ) {
1019 if ( isset( $default ) && $default !== false ) {
1020 // Having a default value of anything other than 'false' is not allowed
1023 "Boolean param $encParamName's default is set to '$default'. " .
1024 "Boolean parameters must default to false."
1028 $value = $this->getMain()->getCheck( $encParamName );
1029 } elseif ( $type == 'upload' ) {
1030 if ( isset( $default ) ) {
1031 // Having a default value is not allowed
1034 "File upload param $encParamName's default is set to " .
1035 "'$default'. File upload parameters may not have a default." );
1038 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1040 $value = $this->getMain()->getUpload( $encParamName );
1041 if ( !$value->exists() ) {
1042 // This will get the value without trying to normalize it
1043 // (because trying to normalize a large binary file
1044 // accidentally uploaded as a field fails spectacularly)
1045 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1046 if ( $value !== null ) {
1048 "File upload param $encParamName is not a file upload; " .
1049 "be sure to use multipart/form-data for your POST and include " .
1050 "a filename in the Content-Disposition header.",
1051 "badupload_{$encParamName}"
1056 $value = $this->getMain()->getVal( $encParamName, $default );
1058 if ( isset( $value ) && $type == 'namespace' ) {
1059 $type = MWNamespace
::getValidNamespaces();
1063 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1064 $value = $this->parseMultiValue(
1068 is_array( $type ) ?
$type : null
1072 // More validation only when choices were not given
1073 // choices were validated in parseMultiValue()
1074 if ( isset( $value ) ) {
1075 if ( !is_array( $type ) ) {
1077 case 'NULL': // nothing to do
1080 if ( $required && $value === '' ) {
1081 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1084 case 'integer': // Force everything using intval() and optionally validate limits
1085 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1086 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1087 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1088 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1090 if ( is_array( $value ) ) {
1091 $value = array_map( 'intval', $value );
1092 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1093 foreach ( $value as &$v ) {
1094 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1098 $value = intval( $value );
1099 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1100 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1105 if ( !$parseLimit ) {
1106 // Don't do any validation whatsoever
1109 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1110 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1114 "MAX1 or MAX2 are not defined for the limit $encParamName"
1118 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1120 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1121 if ( $value == 'max' ) {
1122 $value = $this->getMain()->canApiHighLimits()
1123 ?
$paramSettings[self
::PARAM_MAX2
]
1124 : $paramSettings[self
::PARAM_MAX
];
1125 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1127 $value = intval( $value );
1128 $this->validateLimit(
1132 $paramSettings[self
::PARAM_MAX
],
1133 $paramSettings[self
::PARAM_MAX2
]
1139 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1143 if ( is_array( $value ) ) {
1144 foreach ( $value as $key => $val ) {
1145 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1148 $value = $this->validateTimestamp( $value, $encParamName );
1152 if ( is_array( $value ) ) {
1153 foreach ( $value as $key => $val ) {
1154 $value[$key] = $this->validateUser( $val, $encParamName );
1157 $value = $this->validateUser( $value, $encParamName );
1160 case 'upload': // nothing to do
1163 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1167 // Throw out duplicates if requested
1168 if ( !$dupes && is_array( $value ) ) {
1169 $value = array_unique( $value );
1172 // Set a warning if a deprecated parameter has been passed
1173 if ( $deprecated && $value !== false ) {
1174 $this->setWarning( "The $encParamName parameter has been deprecated." );
1176 } elseif ( $required ) {
1177 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1184 * Return an array of values that were given in a 'a|b|c' notation,
1185 * after it optionally validates them against the list allowed values.
1187 * @param string $valueName The name of the parameter (for error
1189 * @param mixed $value The value being parsed
1190 * @param bool $allowMultiple Can $value contain more than one value
1192 * @param string[]|null $allowedValues An array of values to check against. If
1193 * null, all values are accepted.
1194 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1196 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1197 if ( trim( $value ) === '' && $allowMultiple ) {
1201 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1202 // because it unstubs $wgUser
1203 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1204 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1208 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1209 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1210 "the limit is $sizeLimit" );
1213 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1214 // Bug 33482 - Allow entries with | in them for non-multiple values
1215 if ( in_array( $value, $allowedValues, true ) ) {
1219 $possibleValues = is_array( $allowedValues )
1220 ?
"of '" . implode( "', '", $allowedValues ) . "'"
1223 "Only one $possibleValues is allowed for parameter '$valueName'",
1224 "multival_$valueName"
1228 if ( is_array( $allowedValues ) ) {
1229 // Check for unknown values
1230 $unknown = array_diff( $valuesList, $allowedValues );
1231 if ( count( $unknown ) ) {
1232 if ( $allowMultiple ) {
1233 $s = count( $unknown ) > 1 ?
's' : '';
1234 $vals = implode( ", ", $unknown );
1235 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1238 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1239 "unknown_$valueName"
1243 // Now throw them out
1244 $valuesList = array_intersect( $valuesList, $allowedValues );
1247 return $allowMultiple ?
$valuesList : $valuesList[0];
1251 * Validate the value against the minimum and user/bot maximum limits.
1252 * Prints usage info on failure.
1253 * @param string $paramName Parameter name
1254 * @param int $value Parameter value
1255 * @param int|null $min Minimum value
1256 * @param int|null $max Maximum value for users
1257 * @param int $botMax Maximum value for sysops/bots
1258 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1260 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1261 if ( !is_null( $min ) && $value < $min ) {
1263 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1264 $this->warnOrDie( $msg, $enforceLimits );
1268 // Minimum is always validated, whereas maximum is checked only if not
1269 // running in internal call mode
1270 if ( $this->getMain()->isInternalMode() ) {
1274 // Optimization: do not check user's bot status unless really needed -- skips db query
1275 // assumes $botMax >= $max
1276 if ( !is_null( $max ) && $value > $max ) {
1277 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1278 if ( $value > $botMax ) {
1279 $msg = $this->encodeParamName( $paramName ) .
1280 " may not be over $botMax (set to $value) for bots or sysops";
1281 $this->warnOrDie( $msg, $enforceLimits );
1285 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1286 $this->warnOrDie( $msg, $enforceLimits );
1293 * Validate and normalize of parameters of type 'timestamp'
1294 * @param string $value Parameter value
1295 * @param string $encParamName Parameter name
1296 * @return string Validated and normalized parameter
1298 function validateTimestamp( $value, $encParamName ) {
1299 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1300 if ( $unixTimestamp === false ) {
1302 "Invalid value '$value' for timestamp parameter $encParamName",
1303 "badtimestamp_{$encParamName}"
1307 return wfTimestamp( TS_MW
, $unixTimestamp );
1311 * Validate and normalize of parameters of type 'user'
1312 * @param string $value Parameter value
1313 * @param string $encParamName Parameter name
1314 * @return string Validated and normalized parameter
1316 private function validateUser( $value, $encParamName ) {
1317 $title = Title
::makeTitleSafe( NS_USER
, $value );
1318 if ( $title === null ) {
1320 "Invalid value '$value' for user parameter $encParamName",
1321 "baduser_{$encParamName}"
1325 return $title->getText();
1329 * Adds a warning to the output, else dies
1331 * @param string $msg Message to show as a warning, or error message if dying
1332 * @param bool $enforceLimits Whether this is an enforce (die)
1334 private function warnOrDie( $msg, $enforceLimits = false ) {
1335 if ( $enforceLimits ) {
1336 $this->dieUsage( $msg, 'integeroutofrange' );
1339 $this->setWarning( $msg );
1343 * Truncate an array to a certain length.
1344 * @param array $arr Array to truncate
1345 * @param int $limit Maximum length
1346 * @return bool True if the array was truncated, false otherwise
1348 public static function truncateArray( &$arr, $limit ) {
1350 while ( count( $arr ) > $limit ) {
1359 * Throw a UsageException, which will (if uncaught) call the main module's
1360 * error handler and die with an error message.
1362 * @param string $description One-line human-readable description of the
1363 * error condition, e.g., "The API requires a valid action parameter"
1364 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1365 * automated identification of the error, e.g., 'unknown_action'
1366 * @param int $httpRespCode HTTP response code
1367 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1368 * @throws UsageException
1370 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1371 Profiler
::instance()->close();
1372 throw new UsageException(
1374 $this->encodeParamName( $errorCode ),
1381 * Get error (as code, string) from a Status object.
1384 * @param Status $status
1385 * @return array Array of code and error string
1387 public function getErrorFromStatus( $status ) {
1388 if ( $status->isGood() ) {
1389 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1392 $errors = $status->getErrorsArray();
1394 // No errors? Assume the warnings should be treated as errors
1395 $errors = $status->getWarningsArray();
1398 // Still no errors? Punt
1399 $errors = array( array( 'unknownerror-nocode' ) );
1402 // Cannot use dieUsageMsg() because extensions might return custom
1404 if ( $errors[0] instanceof Message
) {
1406 $code = $msg->getKey();
1408 $code = array_shift( $errors[0] );
1409 $msg = wfMessage( $code, $errors[0] );
1411 if ( isset( ApiBase
::$messageMap[$code] ) ) {
1412 // Translate message to code, for backwards compatability
1413 $code = ApiBase
::$messageMap[$code]['code'];
1416 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1420 * Throw a UsageException based on the errors in the Status object.
1423 * @param Status $status
1424 * @throws MWException
1426 public function dieStatus( $status ) {
1428 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1429 $this->dieUsage( $msg, $code );
1432 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1434 * Array that maps message keys to error messages. $1 and friends are replaced.
1436 public static $messageMap = array(
1437 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1438 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1439 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1441 // Messages from Title::getUserPermissionsErrors()
1442 'ns-specialprotected' => array(
1443 'code' => 'unsupportednamespace',
1444 'info' => "Pages in the Special namespace can't be edited"
1446 'protectedinterface' => array(
1447 'code' => 'protectednamespace-interface',
1448 'info' => "You're not allowed to edit interface messages"
1450 'namespaceprotected' => array(
1451 'code' => 'protectednamespace',
1452 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1454 'customcssprotected' => array(
1455 'code' => 'customcssprotected',
1456 'info' => "You're not allowed to edit custom CSS pages"
1458 'customjsprotected' => array(
1459 'code' => 'customjsprotected',
1460 'info' => "You're not allowed to edit custom JavaScript pages"
1462 'cascadeprotected' => array(
1463 'code' => 'cascadeprotected',
1464 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1466 'protectedpagetext' => array(
1467 'code' => 'protectedpage',
1468 'info' => "The \"\$1\" right is required to edit this page"
1470 'protect-cantedit' => array(
1471 'code' => 'cantedit',
1472 'info' => "You can't protect this page because you can't edit it"
1474 'badaccess-group0' => array(
1475 'code' => 'permissiondenied',
1476 'info' => "Permission denied"
1477 ), // Generic permission denied message
1478 'badaccess-groups' => array(
1479 'code' => 'permissiondenied',
1480 'info' => "Permission denied"
1482 'titleprotected' => array(
1483 'code' => 'protectedtitle',
1484 'info' => "This title has been protected from creation"
1486 'nocreate-loggedin' => array(
1487 'code' => 'cantcreate',
1488 'info' => "You don't have permission to create new pages"
1490 'nocreatetext' => array(
1491 'code' => 'cantcreate-anon',
1492 'info' => "Anonymous users can't create new pages"
1494 'movenologintext' => array(
1495 'code' => 'cantmove-anon',
1496 'info' => "Anonymous users can't move pages"
1498 'movenotallowed' => array(
1499 'code' => 'cantmove',
1500 'info' => "You don't have permission to move pages"
1502 'confirmedittext' => array(
1503 'code' => 'confirmemail',
1504 'info' => "You must confirm your email address before you can edit"
1506 'blockedtext' => array(
1507 'code' => 'blocked',
1508 'info' => "You have been blocked from editing"
1510 'autoblockedtext' => array(
1511 'code' => 'autoblocked',
1512 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1515 // Miscellaneous interface messages
1516 'actionthrottledtext' => array(
1517 'code' => 'ratelimited',
1518 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1520 'alreadyrolled' => array(
1521 'code' => 'alreadyrolled',
1522 'info' => "The page you tried to rollback was already rolled back"
1524 'cantrollback' => array(
1525 'code' => 'onlyauthor',
1526 'info' => "The page you tried to rollback only has one author"
1528 'readonlytext' => array(
1529 'code' => 'readonly',
1530 'info' => "The wiki is currently in read-only mode"
1532 'sessionfailure' => array(
1533 'code' => 'badtoken',
1534 'info' => "Invalid token" ),
1535 'cannotdelete' => array(
1536 'code' => 'cantdelete',
1537 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1539 'notanarticle' => array(
1540 'code' => 'missingtitle',
1541 'info' => "The page you requested doesn't exist"
1543 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1545 'immobile_namespace' => array(
1546 'code' => 'immobilenamespace',
1547 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1549 'articleexists' => array(
1550 'code' => 'articleexists',
1551 'info' => "The destination article already exists and is not a redirect to the source article"
1553 'protectedpage' => array(
1554 'code' => 'protectedpage',
1555 'info' => "You don't have permission to perform this move"
1557 'hookaborted' => array(
1558 'code' => 'hookaborted',
1559 'info' => "The modification you tried to make was aborted by an extension hook"
1561 'cantmove-titleprotected' => array(
1562 'code' => 'protectedtitle',
1563 'info' => "The destination article has been protected from creation"
1565 'imagenocrossnamespace' => array(
1566 'code' => 'nonfilenamespace',
1567 'info' => "Can't move a file to a non-file namespace"
1569 'imagetypemismatch' => array(
1570 'code' => 'filetypemismatch',
1571 'info' => "The new file extension doesn't match its type"
1573 // 'badarticleerror' => shouldn't happen
1574 // 'badtitletext' => shouldn't happen
1575 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1576 'range_block_disabled' => array(
1577 'code' => 'rangedisabled',
1578 'info' => "Blocking IP ranges has been disabled"
1580 'nosuchusershort' => array(
1581 'code' => 'nosuchuser',
1582 'info' => "The user you specified doesn't exist"
1584 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1585 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1586 'ipb_already_blocked' => array(
1587 'code' => 'alreadyblocked',
1588 'info' => "The user you tried to block was already blocked"
1590 'ipb_blocked_as_range' => array(
1591 'code' => 'blockedasrange',
1592 '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."
1594 'ipb_cant_unblock' => array(
1595 'code' => 'cantunblock',
1596 'info' => "The block you specified was not found. It may have been unblocked already"
1598 'mailnologin' => array(
1599 'code' => 'cantsend',
1600 '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"
1602 'ipbblocked' => array(
1603 'code' => 'ipbblocked',
1604 'info' => 'You cannot block or unblock users while you are yourself blocked'
1606 'ipbnounblockself' => array(
1607 'code' => 'ipbnounblockself',
1608 'info' => 'You are not allowed to unblock yourself'
1610 'usermaildisabled' => array(
1611 'code' => 'usermaildisabled',
1612 'info' => "User email has been disabled"
1614 'blockedemailuser' => array(
1615 'code' => 'blockedfrommail',
1616 'info' => "You have been blocked from sending email"
1618 'notarget' => array(
1619 'code' => 'notarget',
1620 'info' => "You have not specified a valid target for this action"
1623 'code' => 'noemail',
1624 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1626 'rcpatroldisabled' => array(
1627 'code' => 'patroldisabled',
1628 'info' => "Patrolling is disabled on this wiki"
1630 'markedaspatrollederror-noautopatrol' => array(
1631 'code' => 'noautopatrol',
1632 'info' => "You don't have permission to patrol your own changes"
1634 'delete-toobig' => array(
1635 'code' => 'bigdelete',
1636 'info' => "You can't delete this page because it has more than \$1 revisions"
1638 'movenotallowedfile' => array(
1639 'code' => 'cantmovefile',
1640 'info' => "You don't have permission to move files"
1642 'userrights-no-interwiki' => array(
1643 'code' => 'nointerwikiuserrights',
1644 'info' => "You don't have permission to change user rights on other wikis"
1646 'userrights-nodatabase' => array(
1647 'code' => 'nosuchdatabase',
1648 'info' => "Database \"\$1\" does not exist or is not local"
1650 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1651 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1652 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1653 'import-rootpage-invalid' => array(
1654 'code' => 'import-rootpage-invalid',
1655 'info' => 'Root page is an invalid title'
1657 'import-rootpage-nosubpage' => array(
1658 'code' => 'import-rootpage-nosubpage',
1659 'info' => 'Namespace "$1" of the root page does not allow subpages'
1662 // API-specific messages
1663 'readrequired' => array(
1664 'code' => 'readapidenied',
1665 'info' => "You need read permission to use this module"
1667 'writedisabled' => array(
1668 'code' => 'noapiwrite',
1669 '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"
1671 'writerequired' => array(
1672 'code' => 'writeapidenied',
1673 'info' => "You're not allowed to edit this wiki through the API"
1675 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1676 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1677 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1678 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1679 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1680 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1681 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1682 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1683 'create-titleexists' => array(
1684 'code' => 'create-titleexists',
1685 'info' => "Existing titles can't be protected with 'create'"
1687 'missingtitle-createonly' => array(
1688 'code' => 'missingtitle-createonly',
1689 'info' => "Missing titles can only be protected with 'create'"
1691 'cantblock' => array( 'code' => 'cantblock',
1692 'info' => "You don't have permission to block users"
1694 'canthide' => array(
1695 'code' => 'canthide',
1696 'info' => "You don't have permission to hide user names from the block log"
1698 'cantblock-email' => array(
1699 'code' => 'cantblock-email',
1700 'info' => "You don't have permission to block users from sending email through the wiki"
1702 'unblock-notarget' => array(
1703 'code' => 'notarget',
1704 'info' => "Either the id or the user parameter must be set"
1706 'unblock-idanduser' => array(
1707 'code' => 'idanduser',
1708 'info' => "The id and user parameters can't be used together"
1710 'cantunblock' => array(
1711 'code' => 'permissiondenied',
1712 'info' => "You don't have permission to unblock users"
1714 'cannotundelete' => array(
1715 'code' => 'cantundelete',
1716 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1718 'permdenied-undelete' => array(
1719 'code' => 'permissiondenied',
1720 'info' => "You don't have permission to restore deleted revisions"
1722 'createonly-exists' => array(
1723 'code' => 'articleexists',
1724 'info' => "The article you tried to create has been created already"
1726 'nocreate-missing' => array(
1727 'code' => 'missingtitle',
1728 'info' => "The article you tried to edit doesn't exist"
1730 'nosuchrcid' => array(
1731 'code' => 'nosuchrcid',
1732 'info' => "There is no change with rcid \"\$1\""
1734 'protect-invalidaction' => array(
1735 'code' => 'protect-invalidaction',
1736 'info' => "Invalid protection type \"\$1\""
1738 'protect-invalidlevel' => array(
1739 'code' => 'protect-invalidlevel',
1740 'info' => "Invalid protection level \"\$1\""
1742 'toofewexpiries' => array(
1743 'code' => 'toofewexpiries',
1744 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1746 'cantimport' => array(
1747 'code' => 'cantimport',
1748 'info' => "You don't have permission to import pages"
1750 'cantimport-upload' => array(
1751 'code' => 'cantimport-upload',
1752 'info' => "You don't have permission to import uploaded pages"
1754 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1755 'importuploaderrorsize' => array(
1756 'code' => 'filetoobig',
1757 'info' => 'The file you uploaded is bigger than the maximum upload size'
1759 'importuploaderrorpartial' => array(
1760 'code' => 'partialupload',
1761 'info' => 'The file was only partially uploaded'
1763 'importuploaderrortemp' => array(
1764 'code' => 'notempdir',
1765 'info' => 'The temporary upload directory is missing'
1767 'importcantopen' => array(
1768 'code' => 'cantopenfile',
1769 'info' => "Couldn't open the uploaded file"
1771 'import-noarticle' => array(
1772 'code' => 'badinterwiki',
1773 'info' => 'Invalid interwiki title specified'
1775 'importbadinterwiki' => array(
1776 'code' => 'badinterwiki',
1777 'info' => 'Invalid interwiki title specified'
1779 'import-unknownerror' => array(
1780 'code' => 'import-unknownerror',
1781 'info' => "Unknown error on import: \"\$1\""
1783 'cantoverwrite-sharedfile' => array(
1784 'code' => 'cantoverwrite-sharedfile',
1785 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1787 'sharedfile-exists' => array(
1788 'code' => 'fileexists-sharedrepo-perm',
1789 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1791 'mustbeposted' => array(
1792 'code' => 'mustbeposted',
1793 'info' => "The \$1 module requires a POST request"
1797 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1799 'specialpage-cantexecute' => array(
1800 'code' => 'specialpage-cantexecute',
1801 'info' => "You don't have permission to view the results of this special page"
1803 'invalidoldimage' => array(
1804 'code' => 'invalidoldimage',
1805 'info' => 'The oldimage parameter has invalid format'
1807 'nodeleteablefile' => array(
1808 'code' => 'nodeleteablefile',
1809 'info' => 'No such old version of the file'
1811 'fileexists-forbidden' => array(
1812 'code' => 'fileexists-forbidden',
1813 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1815 'fileexists-shared-forbidden' => array(
1816 'code' => 'fileexists-shared-forbidden',
1817 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1819 'filerevert-badversion' => array(
1820 'code' => 'filerevert-badversion',
1821 'info' => 'There is no previous local version of this file with the provided timestamp.'
1824 // ApiEditPage messages
1825 'noimageredirect-anon' => array(
1826 'code' => 'noimageredirect-anon',
1827 'info' => "Anonymous users can't create image redirects"
1829 'noimageredirect-logged' => array(
1830 'code' => 'noimageredirect',
1831 'info' => "You don't have permission to create image redirects"
1833 'spamdetected' => array(
1834 'code' => 'spamdetected',
1835 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1837 'contenttoobig' => array(
1838 'code' => 'contenttoobig',
1839 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1841 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1842 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1843 'wasdeleted' => array(
1844 'code' => 'pagedeleted',
1845 'info' => "The page has been deleted since you fetched its timestamp"
1847 'blankpage' => array(
1848 'code' => 'emptypage',
1849 'info' => "Creating new, empty pages is not allowed"
1851 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1852 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1853 'missingtext' => array(
1855 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1857 'emptynewsection' => array(
1858 'code' => 'emptynewsection',
1859 'info' => 'Creating empty new sections is not possible.'
1861 'revwrongpage' => array(
1862 'code' => 'revwrongpage',
1863 'info' => "r\$1 is not a revision of \"\$2\""
1865 'undo-failure' => array(
1866 'code' => 'undofailure',
1867 'info' => 'Undo failed due to conflicting intermediate edits'
1870 // Messages from WikiPage::doEit()
1871 'edit-hook-aborted' => array(
1872 'code' => 'edit-hook-aborted',
1873 'info' => "Your edit was aborted by an ArticleSave hook"
1875 'edit-gone-missing' => array(
1876 'code' => 'edit-gone-missing',
1877 'info' => "The page you tried to edit doesn't seem to exist anymore"
1879 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1880 'edit-already-exists' => array(
1881 'code' => 'edit-already-exists',
1882 'info' => 'It seems the page you tried to create already exist'
1886 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1887 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1888 'uploaddisabled' => array(
1889 'code' => 'uploaddisabled',
1890 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1892 'copyuploaddisabled' => array(
1893 'code' => 'copyuploaddisabled',
1894 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1896 'copyuploadbaddomain' => array(
1897 'code' => 'copyuploadbaddomain',
1898 'info' => 'Uploads by URL are not allowed from this domain.'
1900 'copyuploadbadurl' => array(
1901 'code' => 'copyuploadbadurl',
1902 'info' => 'Upload not allowed from this URL.'
1905 'filename-tooshort' => array(
1906 'code' => 'filename-tooshort',
1907 'info' => 'The filename is too short'
1909 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1910 'illegal-filename' => array(
1911 'code' => 'illegal-filename',
1912 'info' => 'The filename is not allowed'
1914 'filetype-missing' => array(
1915 'code' => 'filetype-missing',
1916 'info' => 'The file is missing an extension'
1919 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1921 // @codingStandardsIgnoreEnd
1924 * Helper function for readonly errors
1926 public function dieReadOnly() {
1927 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1928 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1929 array( 'readonlyreason' => wfReadOnlyReason() ) );
1933 * Output the error message related to a certain array
1934 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1936 public function dieUsageMsg( $error ) {
1937 # most of the time we send a 1 element, so we might as well send it as
1938 # a string and make this an array here.
1939 if ( is_string( $error ) ) {
1940 $error = array( $error );
1942 $parsed = $this->parseMsg( $error );
1943 $this->dieUsage( $parsed['info'], $parsed['code'] );
1947 * Will only set a warning instead of failing if the global $wgDebugAPI
1948 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1949 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1952 public function dieUsageMsgOrDebug( $error ) {
1953 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1954 $this->dieUsageMsg( $error );
1957 if ( is_string( $error ) ) {
1958 $error = array( $error );
1960 $parsed = $this->parseMsg( $error );
1961 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1965 * Die with the $prefix.'badcontinue' error. This call is common enough to
1966 * make it into the base method.
1967 * @param bool $condition Will only die if this value is true
1970 protected function dieContinueUsageIf( $condition ) {
1973 'Invalid continue param. You should pass the original value returned by the previous query',
1979 * Return the error message related to a certain array
1980 * @param array $error Element of a getUserPermissionsErrors()-style array
1981 * @return array('code' => code, 'info' => info)
1983 public function parseMsg( $error ) {
1984 $error = (array)$error; // It seems strings sometimes make their way in here
1985 $key = array_shift( $error );
1987 // Check whether the error array was nested
1988 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1989 if ( is_array( $key ) ) {
1991 $key = array_shift( $error );
1994 if ( isset( self
::$messageMap[$key] ) ) {
1996 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1997 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
2001 // If the key isn't present, throw an "unknown error"
2002 return $this->parseMsg( array( 'unknownerror', $key ) );
2006 * Internal code errors should be reported with this method
2007 * @param string $method Method or function name
2008 * @param string $message Error message
2009 * @throws MWException
2011 protected static function dieDebug( $method, $message ) {
2012 throw new MWException( "Internal error in $method: $message" );
2016 * Indicates if this module needs maxlag to be checked
2019 public function shouldCheckMaxlag() {
2024 * Indicates whether this module requires read rights
2027 public function isReadMode() {
2032 * Indicates whether this module requires write mode
2035 public function isWriteMode() {
2040 * Indicates whether this module must be called with a POST request
2043 public function mustBePosted() {
2048 * Returns whether this module requires a token to execute
2049 * It is used to show possible errors in action=paraminfo
2053 public function needsToken() {
2058 * Returns the token salt if there is one,
2059 * '' if the module doesn't require a salt,
2060 * else false if the module doesn't need a token
2061 * You have also to override needsToken()
2062 * Value is passed to User::getEditToken
2063 * @return bool|string|array
2065 public function getTokenSalt() {
2070 * Gets the user for whom to get the watchlist
2072 * @param array $params
2075 public function getWatchlistUser( $params ) {
2076 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2077 $user = User
::newFromName( $params['owner'], false );
2078 if ( !( $user && $user->getId() ) ) {
2079 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2081 $token = $user->getOption( 'watchlisttoken' );
2082 if ( $token == '' ||
$token != $params['token'] ) {
2084 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2089 if ( !$this->getUser()->isLoggedIn() ) {
2090 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2092 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2093 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2095 $user = $this->getUser();
2102 * @return bool|string|array Returns a false if the module has no help URL,
2103 * else returns a (array of) string
2105 public function getHelpUrls() {
2110 * Returns a list of all possible errors returned by the module
2112 * Don't call this function directly: use getFinalPossibleErrors() to allow
2113 * hooks to modify parameters as needed.
2115 * @return array Array in the format of array( key, param1, param2, ... )
2116 * or array( 'code' => ..., 'info' => ... )
2118 public function getPossibleErrors() {
2121 $params = $this->getFinalParams();
2123 foreach ( $params as $paramName => $paramSettings ) {
2124 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] )
2125 && $paramSettings[ApiBase
::PARAM_REQUIRED
]
2127 $ret[] = array( 'missingparam', $paramName );
2130 if ( array_key_exists( 'continue', $params ) ) {
2132 'code' => 'badcontinue',
2133 'info' => 'Invalid continue param. You should pass the ' .
2134 'original value returned by the previous query'
2139 if ( $this->mustBePosted() ) {
2140 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2143 if ( $this->isReadMode() ) {
2144 $ret[] = array( 'readrequired' );
2147 if ( $this->isWriteMode() ) {
2148 $ret[] = array( 'writerequired' );
2149 $ret[] = array( 'writedisabled' );
2152 if ( $this->needsToken() ) {
2153 if ( !isset( $params['token'][ApiBase
::PARAM_REQUIRED
] )
2154 ||
!$params['token'][ApiBase
::PARAM_REQUIRED
]
2156 // Add token as possible missing parameter, if not already done
2157 $ret[] = array( 'missingparam', 'token' );
2159 $ret[] = array( 'sessionfailure' );
2166 * Get final list of possible errors, after hooks have had a chance to
2167 * tweak it as needed.
2172 public function getFinalPossibleErrors() {
2173 $possibleErrors = $this->getPossibleErrors();
2174 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2176 return $possibleErrors;
2180 * Parses a list of errors into a standardised format
2181 * @param array $errors List of errors. Items can be in the for
2182 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2183 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2185 public function parseErrors( $errors ) {
2188 foreach ( $errors as $row ) {
2189 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2192 $ret[] = $this->parseMsg( $row );
2200 * Profiling: total module execution time
2202 private $mTimeIn = 0, $mModuleTime = 0;
2205 * Start module profiling
2207 public function profileIn() {
2208 if ( $this->mTimeIn
!== 0 ) {
2209 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileOut()' );
2211 $this->mTimeIn
= microtime( true );
2212 wfProfileIn( $this->getModuleProfileName() );
2216 * End module profiling
2218 public function profileOut() {
2219 if ( $this->mTimeIn
=== 0 ) {
2220 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileIn() first' );
2222 if ( $this->mDBTimeIn
!== 0 ) {
2225 'Must be called after database profiling is done with profileDBOut()'
2229 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
2231 wfProfileOut( $this->getModuleProfileName() );
2235 * When modules crash, sometimes it is needed to do a profileOut() regardless
2236 * of the profiling state the module was in. This method does such cleanup.
2238 public function safeProfileOut() {
2239 if ( $this->mTimeIn
!== 0 ) {
2240 if ( $this->mDBTimeIn
!== 0 ) {
2241 $this->profileDBOut();
2243 $this->profileOut();
2248 * Total time the module was executed
2251 public function getProfileTime() {
2252 if ( $this->mTimeIn
!== 0 ) {
2253 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileOut() first' );
2256 return $this->mModuleTime
;
2260 * Profiling: database execution time
2262 private $mDBTimeIn = 0, $mDBTime = 0;
2265 * Start module profiling
2267 public function profileDBIn() {
2268 if ( $this->mTimeIn
=== 0 ) {
2271 'Must be called while profiling the entire module with profileIn()'
2274 if ( $this->mDBTimeIn
!== 0 ) {
2275 ApiBase
::dieDebug( __METHOD__
, 'Called twice without calling profileDBOut()' );
2277 $this->mDBTimeIn
= microtime( true );
2278 wfProfileIn( $this->getModuleProfileName( true ) );
2282 * End database profiling
2284 public function profileDBOut() {
2285 if ( $this->mTimeIn
=== 0 ) {
2286 ApiBase
::dieDebug( __METHOD__
, 'Must be called while profiling ' .
2287 'the entire module with profileIn()' );
2289 if ( $this->mDBTimeIn
=== 0 ) {
2290 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBIn() first' );
2293 $time = microtime( true ) - $this->mDBTimeIn
;
2294 $this->mDBTimeIn
= 0;
2296 $this->mDBTime +
= $time;
2297 $this->getMain()->mDBTime +
= $time;
2298 wfProfileOut( $this->getModuleProfileName( true ) );
2302 * Total time the module used the database
2305 public function getProfileDBTime() {
2306 if ( $this->mDBTimeIn
!== 0 ) {
2307 ApiBase
::dieDebug( __METHOD__
, 'Called without calling profileDBOut() first' );
2310 return $this->mDBTime
;
2314 * Gets a default slave database connection object
2315 * @return DatabaseBase
2317 protected function getDB() {
2318 if ( !isset( $this->mSlaveDB
) ) {
2319 $this->profileDBIn();
2320 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
2321 $this->profileDBOut();
2324 return $this->mSlaveDB
;
2328 * Debugging function that prints a value and an optional backtrace
2329 * @param mixed $value Value to print
2330 * @param string $name Description of the printed value
2331 * @param bool $backtrace If true, print a backtrace
2333 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2334 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2335 var_export( $value );
2337 print "\n" . wfBacktrace();