5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This abstract class implements many basic API functions, and is the base of
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
38 * Self-documentation: code to allow the API to document its own state
42 abstract class ApiBase
extends ContextSource
{
44 // These constants allow modules to specify exactly how to treat incoming parameters.
46 const PARAM_DFLT
= 0; // Default value of the parameter
47 const PARAM_ISMULTI
= 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE
= 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX
= 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2
= 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN
= 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES
= 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED
= 7; // Boolean, is the parameter deprecated (will show a warning)
55 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
57 const PARAM_RANGE_ENFORCE
= 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
59 const PROP_ROOT
= 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
60 const PROP_LIST
= 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
61 const PROP_TYPE
= 0; // Type of the property, uses same format as PARAM_TYPE
62 const PROP_NULLABLE
= 1; // Boolean, can the property be not included in the result? Defaults to false
64 const LIMIT_BIG1
= 500; // Fast query, std user limit
65 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
66 const LIMIT_SML1
= 50; // Slow query, std user limit
67 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
70 * getAllowedParams() flag: When set, the result could take longer to generate,
71 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
74 const GET_VALUES_FOR_HELP
= 1;
76 private $mMainModule, $mModuleName, $mModulePrefix;
77 private $mSlaveDB = null;
78 private $mParamCache = array();
82 * @param $mainModule ApiMain object
83 * @param $moduleName string Name of this module
84 * @param $modulePrefix string Prefix to use for parameter names
86 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
87 $this->mMainModule
= $mainModule;
88 $this->mModuleName
= $moduleName;
89 $this->mModulePrefix
= $modulePrefix;
91 if ( !$this->isMain() ) {
92 $this->setContext( $mainModule->getContext() );
96 /*****************************************************************************
98 *****************************************************************************/
101 * Evaluates the parameters, performs the requested query, and sets up
102 * the result. Concrete implementations of ApiBase must override this
103 * method to provide whatever functionality their module offers.
104 * Implementations must not produce any output on their own and are not
105 * expected to handle any errors.
107 * The execute() method will be invoked directly by ApiMain immediately
108 * before the result of the module is output. Aside from the
109 * constructor, implementations should assume that no other methods
110 * will be called externally on the module before the result is
113 * The result data should be stored in the ApiResult object available
114 * through getResult().
116 abstract public function execute();
119 * Returns a string that identifies the version of the extending class.
120 * Typically includes the class name, the svn revision, timestamp, and
121 * last author. Usually done with SVN's Id keyword
123 * @deprecated since 1.21, version string is no longer supported
125 public function getVersion() {
126 wfDeprecated( __METHOD__
, '1.21' );
131 * Get the name of the module being executed by this instance
134 public function getModuleName() {
135 return $this->mModuleName
;
139 * Get the module manager, or null if this module has no sub-modules
141 * @return ApiModuleManager
143 public function getModuleManager() {
148 * Get parameter prefix (usually two letters or an empty string).
151 public function getModulePrefix() {
152 return $this->mModulePrefix
;
156 * Get the name of the module as shown in the profiler log
158 * @param $db DatabaseBase|bool
162 public function getModuleProfileName( $db = false ) {
164 return 'API:' . $this->mModuleName
. '-DB';
166 return 'API:' . $this->mModuleName
;
171 * Get the main module
172 * @return ApiMain object
174 public function getMain() {
175 return $this->mMainModule
;
179 * Returns true if this module is the main module ($this === $this->mMainModule),
183 public function isMain() {
184 return $this === $this->mMainModule
;
188 * Get the result object
191 public function getResult() {
192 // Main module has getResult() method overridden
193 // Safety - avoid infinite loop:
194 if ( $this->isMain() ) {
195 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
197 return $this->getMain()->getResult();
201 * Get the result data array (read-only)
204 public function getResultData() {
205 return $this->getResult()->getData();
209 * Create a new RequestContext object to use e.g. for calls to other parts
211 * The object will have the WebRequest and the User object set to the ones
212 * used in this instance.
214 * @deprecated since 1.19 use getContext to get the current context
215 * @return DerivativeContext
217 public function createContext() {
218 wfDeprecated( __METHOD__
, '1.19' );
219 return new DerivativeContext( $this->getContext() );
223 * Set warning section for this module. Users should monitor this
224 * section to notice any changes in API. Multiple calls to this
225 * function will result in the warning messages being separated by
227 * @param $warning string Warning message
229 public function setWarning( $warning ) {
230 $result = $this->getResult();
231 $data = $result->getData();
232 $moduleName = $this->getModuleName();
233 if ( isset( $data['warnings'][$moduleName] ) ) {
234 // Don't add duplicate warnings
235 $oldWarning = $data['warnings'][$moduleName]['*'];
236 $warnPos = strpos( $oldWarning, $warning );
237 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
238 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
239 // Check if $warning is followed by "\n" or the end of the $oldWarning
240 $warnPos +
= strlen( $warning );
241 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
245 // If there is a warning already, append it to the existing one
246 $warning = "$oldWarning\n$warning";
249 ApiResult
::setContent( $msg, $warning );
250 $result->disableSizeCheck();
251 $result->addValue( 'warnings', $moduleName,
252 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
253 $result->enableSizeCheck();
257 * If the module may only be used with a certain format module,
258 * it should override this method to return an instance of that formatter.
259 * A value of null means the default format will be used.
260 * @return mixed instance of a derived class of ApiFormatBase, or null
262 public function getCustomPrinter() {
267 * Generates help message for this module, or false if there is no description
268 * @return mixed string or false
270 public function makeHelpMsg() {
271 static $lnPrfx = "\n ";
273 $msg = $this->getFinalDescription();
275 if ( $msg !== false ) {
277 if ( !is_array( $msg ) ) {
282 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
284 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
286 if ( $this->isReadMode() ) {
287 $msg .= "\nThis module requires read rights";
289 if ( $this->isWriteMode() ) {
290 $msg .= "\nThis module requires write rights";
292 if ( $this->mustBePosted() ) {
293 $msg .= "\nThis module only accepts POST requests";
295 if ( $this->isReadMode() ||
$this->isWriteMode() ||
296 $this->mustBePosted() ) {
301 $paramsMsg = $this->makeHelpMsgParameters();
302 if ( $paramsMsg !== false ) {
303 $msg .= "Parameters:\n$paramsMsg";
306 $examples = $this->getExamples();
307 if ( $examples !== false && $examples !== '' ) {
308 if ( !is_array( $examples ) ) {
313 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
314 foreach( $examples as $k => $v ) {
316 if ( is_numeric( $k ) ) {
319 if ( is_array( $v ) ) {
320 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
325 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
335 * @param $item string
338 private function indentExampleText( $item ) {
343 * @param $prefix string Text to split output items
344 * @param $title string What is being output
345 * @param $input string|array
348 protected function makeHelpArrayToString( $prefix, $title, $input ) {
349 if ( $input === false ) {
352 if ( !is_array( $input ) ) {
353 $input = array( $input );
356 if ( count( $input ) > 0 ) {
358 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
362 $msg .= implode( $prefix, $input ) . "\n";
369 * Generates the parameter descriptions for this module, to be displayed in the
371 * @return string or false
373 public function makeHelpMsgParameters() {
374 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
377 $paramsDescription = $this->getFinalParamDescription();
379 $paramPrefix = "\n" . str_repeat( ' ', 24 );
380 $descWordwrap = "\n" . str_repeat( ' ', 28 );
381 foreach ( $params as $paramName => $paramSettings ) {
382 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
383 if ( is_array( $desc ) ) {
384 $desc = implode( $paramPrefix, $desc );
388 if ( !is_array( $paramSettings ) ) {
389 $paramSettings = array(
390 self
::PARAM_DFLT
=> $paramSettings,
394 //handle missing type
395 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
396 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] ) ?
$paramSettings[ApiBase
::PARAM_DFLT
] : null;
397 if ( is_bool( $dflt ) ) {
398 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
399 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
400 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
401 } elseif ( is_int( $dflt ) ) {
402 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
406 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] ) && $paramSettings[self
::PARAM_DEPRECATED
] ) {
407 $desc = "DEPRECATED! $desc";
410 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] ) && $paramSettings[self
::PARAM_REQUIRED
] ) {
411 $desc .= $paramPrefix . "This parameter is required";
414 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
415 if ( isset( $type ) ) {
416 $hintPipeSeparated = true;
417 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
419 $prompt = 'Values (separate with \'|\'): ';
421 $prompt = 'One value: ';
424 if ( is_array( $type ) ) {
427 foreach ( $type as $t ) {
429 $nothingPrompt = 'Can be empty, or ';
434 $desc .= $paramPrefix . $nothingPrompt . $prompt;
435 $choicesstring = implode( ', ', $choices );
436 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
437 $hintPipeSeparated = false;
441 // Special handling because namespaces are type-limited, yet they are not given
442 $desc .= $paramPrefix . $prompt;
443 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
444 100, $descWordwrap );
445 $hintPipeSeparated = false;
448 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
449 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
450 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
455 $s = $multi ?
's' : '';
456 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
457 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
458 if ( $hasMin ||
$hasMax ) {
460 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
461 } elseif ( !$hasMin ) {
462 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
464 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
467 $desc .= $paramPrefix . $intRangeStr;
471 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
477 if ( $hintPipeSeparated ) {
478 $desc .= $paramPrefix . "Separate values with '|'";
481 $isArray = is_array( $type );
483 ||
$isArray && count( $type ) > self
::LIMIT_SML1
) {
484 $desc .= $paramPrefix . "Maximum number of values " .
485 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
490 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
491 if ( !is_null( $default ) && $default !== false ) {
492 $desc .= $paramPrefix . "Default: $default";
495 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
505 * Returns the description string for this module
506 * @return mixed string or array of strings
508 protected function getDescription() {
513 * Returns usage examples for this module. Return false if no examples are available.
514 * @return bool|string|array
516 protected function getExamples() {
521 * Returns an array of allowed parameters (parameter name) => (default
522 * value) or (parameter name) => (array with PARAM_* constants as keys)
523 * Don't call this function directly: use getFinalParams() to allow
524 * hooks to modify parameters as needed.
526 * Some derived classes may choose to handle an integer $flags parameter
527 * in the overriding methods. Callers of this method can pass zero or
528 * more OR-ed flags like GET_VALUES_FOR_HELP.
532 protected function getAllowedParams( /* $flags = 0 */ ) {
533 // int $flags is not declared because it causes "Strict standards"
534 // warning. Most derived classes do not implement it.
539 * Returns an array of parameter descriptions.
540 * Don't call this function directly: use getFinalParamDescription() to
541 * allow hooks to modify descriptions as needed.
542 * @return array|bool False on no parameter descriptions
544 protected function getParamDescription() {
549 * Get final list of parameters, after hooks have had a chance to
550 * tweak it as needed.
552 * @param $flags int Zero or more flags like GET_VALUES_FOR_HELP
553 * @return array|Bool False on no parameters
554 * @since 1.21 $flags param added
556 public function getFinalParams( $flags = 0 ) {
557 $params = $this->getAllowedParams( $flags );
558 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
563 * Get final parameter descriptions, after hooks have had a chance to tweak it as
566 * @return array|bool False on no parameter descriptions
568 public function getFinalParamDescription() {
569 $desc = $this->getParamDescription();
570 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
575 * Returns possible properties in the result, grouped by the value of the prop parameter
578 * Properties that are shown always are in a group with empty string as a key.
579 * Properties that can be shown by several values of prop are included multiple times.
580 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
581 * those on the root object are under the key PROP_ROOT.
582 * The array can also contain a boolean under the key PROP_LIST,
583 * indicating whether the result is a list.
585 * Don't call this function directly: use getFinalResultProperties() to
586 * allow hooks to modify descriptions as needed.
588 * @return array|bool False on no properties
590 protected function getResultProperties() {
595 * Get final possible result properties, after hooks have had a chance to tweak it as
600 public function getFinalResultProperties() {
601 $properties = $this->getResultProperties();
602 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
607 * Add token properties to the array used by getResultProperties,
608 * based on a token functions mapping.
610 protected static function addTokenProperties( &$props, $tokenFunctions ) {
611 foreach ( array_keys( $tokenFunctions ) as $token ) {
612 $props[''][$token . 'token'] = array(
613 ApiBase
::PROP_TYPE
=> 'string',
614 ApiBase
::PROP_NULLABLE
=> true
620 * Get final module description, after hooks have had a chance to tweak it as
623 * @return array|bool False on no parameters
625 public function getFinalDescription() {
626 $desc = $this->getDescription();
627 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
632 * This method mangles parameter name based on the prefix supplied to the constructor.
633 * Override this method to change parameter name during runtime
634 * @param $paramName string Parameter name
635 * @return string Prefixed parameter name
637 public function encodeParamName( $paramName ) {
638 return $this->mModulePrefix
. $paramName;
642 * Using getAllowedParams(), this function makes an array of the values
643 * provided by the user, with key being the name of the variable, and
644 * value - validated value from user or default. limits will not be
645 * parsed if $parseLimit is set to false; use this when the max
646 * limit is not definitive yet, e.g. when getting revisions.
647 * @param $parseLimit Boolean: true by default
650 public function extractRequestParams( $parseLimit = true ) {
651 // Cache parameters, for performance and to avoid bug 24564.
652 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
653 $params = $this->getFinalParams();
656 if ( $params ) { // getFinalParams() can return false
657 foreach ( $params as $paramName => $paramSettings ) {
658 $results[$paramName] = $this->getParameterFromSettings(
659 $paramName, $paramSettings, $parseLimit );
662 $this->mParamCache
[$parseLimit] = $results;
664 return $this->mParamCache
[$parseLimit];
668 * Get a value for the given parameter
669 * @param $paramName string Parameter name
670 * @param $parseLimit bool see extractRequestParams()
671 * @return mixed Parameter value
673 protected function getParameter( $paramName, $parseLimit = true ) {
674 $params = $this->getFinalParams();
675 $paramSettings = $params[$paramName];
676 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
680 * Die if none or more than one of a certain set of parameters is set and not false.
681 * @param $params array of parameter names
683 public function requireOnlyOneParameter( $params ) {
684 $required = func_get_args();
685 array_shift( $required );
686 $p = $this->getModulePrefix();
688 $intersection = array_intersect( array_keys( array_filter( $params,
689 array( $this, "parameterNotEmpty" ) ) ), $required );
691 if ( count( $intersection ) > 1 ) {
692 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
693 } elseif ( count( $intersection ) == 0 ) {
694 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
699 * Generates the possible errors requireOnlyOneParameter() can die with
701 * @param $params array
704 public function getRequireOnlyOneParameterErrorMessages( $params ) {
705 $p = $this->getModulePrefix();
706 $params = implode( ", {$p}", $params );
709 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
710 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
715 * Die if more than one of a certain set of parameters is set and not false.
717 * @param $params array
719 public function requireMaxOneParameter( $params ) {
720 $required = func_get_args();
721 array_shift( $required );
722 $p = $this->getModulePrefix();
724 $intersection = array_intersect( array_keys( array_filter( $params,
725 array( $this, "parameterNotEmpty" ) ) ), $required );
727 if ( count( $intersection ) > 1 ) {
728 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
733 * Generates the possible error requireMaxOneParameter() can die with
735 * @param $params array
738 public function getRequireMaxOneParameterErrorMessages( $params ) {
739 $p = $this->getModulePrefix();
740 $params = implode( ", {$p}", $params );
743 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
748 * @param $params array
749 * @param $load bool|string Whether load the object's state from the database:
750 * - false: don't load (if the pageid is given, it will still be loaded)
751 * - 'fromdb': load from a slave database
752 * - 'fromdbmaster': load from the master database
755 public function getTitleOrPageId( $params, $load = false ) {
756 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
759 if ( isset( $params['title'] ) ) {
760 $titleObj = Title
::newFromText( $params['title'] );
761 if ( !$titleObj ||
$titleObj->isExternal() ) {
762 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
764 if ( !$titleObj->canExist() ) {
765 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
767 $pageObj = WikiPage
::factory( $titleObj );
768 if ( $load !== false ) {
769 $pageObj->loadPageData( $load );
771 } elseif ( isset( $params['pageid'] ) ) {
772 if ( $load === false ) {
775 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
777 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
787 public function getTitleOrPageIdErrorMessage() {
789 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
791 array( 'invalidtitle', 'title' ),
792 array( 'nosuchpageid', 'pageid' ),
798 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
800 * @param $x object Parameter to check is not null/false
803 private function parameterNotEmpty( $x ) {
804 return !is_null( $x ) && $x !== false;
808 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
812 public static function getValidNamespaces() {
813 wfDeprecated( __METHOD__
, '1.17' );
814 return MWNamespace
::getValidNamespaces();
818 * Return true if we're to watch the page, false if not, null if no change.
819 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
820 * @param $titleObj Title the page under consideration
821 * @param $userOption String The user option to consider when $watchlist=preferences.
822 * If not set will magically default to either watchdefault or watchcreations
825 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
827 $userWatching = $this->getUser()->isWatched( $titleObj );
829 switch ( $watchlist ) {
837 # If the user is already watching, don't bother checking
838 if ( $userWatching ) {
841 # If no user option was passed, use watchdefault or watchcreations
842 if ( is_null( $userOption ) ) {
843 $userOption = $titleObj->exists()
844 ?
'watchdefault' : 'watchcreations';
846 # Watch the article based on the user preference
847 return $this->getUser()->getBoolOption( $userOption );
850 return $userWatching;
853 return $userWatching;
858 * Set a watch (or unwatch) based the based on a watchlist parameter.
859 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
860 * @param $titleObj Title the article's title to change
861 * @param $userOption String The user option to consider when $watch=preferences
863 protected function setWatch( $watch, $titleObj, $userOption = null ) {
864 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
865 if ( $value === null ) {
869 $user = $this->getUser();
871 WatchAction
::doWatch( $titleObj, $user );
873 WatchAction
::doUnwatch( $titleObj, $user );
878 * Using the settings determine the value for the given parameter
880 * @param $paramName String: parameter name
881 * @param $paramSettings array|mixed default value or an array of settings
882 * using PARAM_* constants.
883 * @param $parseLimit Boolean: parse limit?
884 * @return mixed Parameter value
886 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
887 // Some classes may decide to change parameter names
888 $encParamName = $this->encodeParamName( $paramName );
890 if ( !is_array( $paramSettings ) ) {
891 $default = $paramSettings;
893 $type = gettype( $paramSettings );
898 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
899 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
900 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
901 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
902 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
903 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
905 // When type is not given, and no choices, the type is the same as $default
906 if ( !isset( $type ) ) {
907 if ( isset( $default ) ) {
908 $type = gettype( $default );
910 $type = 'NULL'; // allow everything
915 if ( $type == 'boolean' ) {
916 if ( isset( $default ) && $default !== false ) {
917 // Having a default value of anything other than 'false' is not allowed
918 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
921 $value = $this->getMain()->getCheck( $encParamName );
922 } elseif ( $type == 'upload' ) {
923 if ( isset( $default ) ) {
924 // Having a default value is not allowed
925 ApiBase
::dieDebug( __METHOD__
, "File upload param $encParamName's default is set to '$default'. File upload parameters may not have a default." );
928 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
930 $value = $this->getMain()->getUpload( $encParamName );
931 if ( !$value->exists() ) {
932 // This will get the value without trying to normalize it
933 // (because trying to normalize a large binary file
934 // accidentally uploaded as a field fails spectacularly)
935 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
936 if ( $value !== null ) {
938 "File upload param $encParamName is not a file upload; " .
939 "be sure to use multipart/form-data for your POST and include " .
940 "a filename in the Content-Disposition header.",
941 "badupload_{$encParamName}"
946 $value = $this->getMain()->getVal( $encParamName, $default );
948 if ( isset( $value ) && $type == 'namespace' ) {
949 $type = MWNamespace
::getValidNamespaces();
953 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
954 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
957 // More validation only when choices were not given
958 // choices were validated in parseMultiValue()
959 if ( isset( $value ) ) {
960 if ( !is_array( $type ) ) {
962 case 'NULL': // nothing to do
965 if ( $required && $value === '' ) {
966 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
969 case 'integer': // Force everything using intval() and optionally validate limits
970 $min = isset ( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
971 $max = isset ( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
972 $enforceLimits = isset ( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
973 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
975 if ( is_array( $value ) ) {
976 $value = array_map( 'intval', $value );
977 if ( !is_null( $min ) ||
!is_null( $max ) ) {
978 foreach ( $value as &$v ) {
979 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
983 $value = intval( $value );
984 if ( !is_null( $min ) ||
!is_null( $max ) ) {
985 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
990 if ( !$parseLimit ) {
991 // Don't do any validation whatsoever
994 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
995 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
998 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1000 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1001 if ( $value == 'max' ) {
1002 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
1003 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1005 $value = intval( $value );
1006 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
1011 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1015 if ( is_array( $value ) ) {
1016 foreach ( $value as $key => $val ) {
1017 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1020 $value = $this->validateTimestamp( $value, $encParamName );
1024 if ( is_array( $value ) ) {
1025 foreach ( $value as $key => $val ) {
1026 $value[$key] = $this->validateUser( $val, $encParamName );
1029 $value = $this->validateUser( $value, $encParamName );
1032 case 'upload': // nothing to do
1035 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1039 // Throw out duplicates if requested
1040 if ( !$dupes && is_array( $value ) ) {
1041 $value = array_unique( $value );
1044 // Set a warning if a deprecated parameter has been passed
1045 if ( $deprecated && $value !== false ) {
1046 $this->setWarning( "The $encParamName parameter has been deprecated." );
1048 } elseif ( $required ) {
1049 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1056 * Return an array of values that were given in a 'a|b|c' notation,
1057 * after it optionally validates them against the list allowed values.
1059 * @param $valueName string The name of the parameter (for error
1061 * @param $value mixed The value being parsed
1062 * @param $allowMultiple bool Can $value contain more than one value
1064 * @param $allowedValues mixed An array of values to check against. If
1065 * null, all values are accepted.
1066 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1068 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1069 if ( trim( $value ) === '' && $allowMultiple ) {
1073 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1074 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1075 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
1076 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
1078 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1079 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1082 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1083 // Bug 33482 - Allow entries with | in them for non-multiple values
1084 if ( in_array( $value, $allowedValues ) ) {
1088 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
1089 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1092 if ( is_array( $allowedValues ) ) {
1093 // Check for unknown values
1094 $unknown = array_diff( $valuesList, $allowedValues );
1095 if ( count( $unknown ) ) {
1096 if ( $allowMultiple ) {
1097 $s = count( $unknown ) > 1 ?
's' : '';
1098 $vals = implode( ", ", $unknown );
1099 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1101 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1104 // Now throw them out
1105 $valuesList = array_intersect( $valuesList, $allowedValues );
1108 return $allowMultiple ?
$valuesList : $valuesList[0];
1112 * Validate the value against the minimum and user/bot maximum limits.
1113 * Prints usage info on failure.
1114 * @param $paramName string Parameter name
1115 * @param $value int Parameter value
1116 * @param $min int|null Minimum value
1117 * @param $max int|null Maximum value for users
1118 * @param $botMax int Maximum value for sysops/bots
1119 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1121 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1122 if ( !is_null( $min ) && $value < $min ) {
1124 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1125 $this->warnOrDie( $msg, $enforceLimits );
1129 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1130 if ( $this->getMain()->isInternalMode() ) {
1134 // Optimization: do not check user's bot status unless really needed -- skips db query
1135 // assumes $botMax >= $max
1136 if ( !is_null( $max ) && $value > $max ) {
1137 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1138 if ( $value > $botMax ) {
1139 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1140 $this->warnOrDie( $msg, $enforceLimits );
1144 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1145 $this->warnOrDie( $msg, $enforceLimits );
1152 * Validate and normalize of parameters of type 'timestamp'
1153 * @param $value string Parameter value
1154 * @param $encParamName string Parameter name
1155 * @return string Validated and normalized parameter
1157 function validateTimestamp( $value, $encParamName ) {
1158 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1159 if ( $unixTimestamp === false ) {
1160 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
1162 return wfTimestamp( TS_MW
, $unixTimestamp );
1166 * Validate and normalize of parameters of type 'user'
1167 * @param $value string Parameter value
1168 * @param $encParamName string Parameter value
1169 * @return string Validated and normalized parameter
1171 private function validateUser( $value, $encParamName ) {
1172 $title = Title
::makeTitleSafe( NS_USER
, $value );
1173 if ( $title === null ) {
1174 $this->dieUsage( "Invalid value '$value' for user parameter $encParamName", "baduser_{$encParamName}" );
1176 return $title->getText();
1180 * Adds a warning to the output, else dies
1182 * @param $msg String Message to show as a warning, or error message if dying
1183 * @param $enforceLimits Boolean Whether this is an enforce (die)
1185 private function warnOrDie( $msg, $enforceLimits = false ) {
1186 if ( $enforceLimits ) {
1187 $this->dieUsage( $msg, 'integeroutofrange' );
1189 $this->setWarning( $msg );
1194 * Truncate an array to a certain length.
1195 * @param $arr array Array to truncate
1196 * @param $limit int Maximum length
1197 * @return bool True if the array was truncated, false otherwise
1199 public static function truncateArray( &$arr, $limit ) {
1201 while ( count( $arr ) > $limit ) {
1209 * Throw a UsageException, which will (if uncaught) call the main module's
1210 * error handler and die with an error message.
1212 * @param $description string One-line human-readable description of the
1213 * error condition, e.g., "The API requires a valid action parameter"
1214 * @param $errorCode string Brief, arbitrary, stable string to allow easy
1215 * automated identification of the error, e.g., 'unknown_action'
1216 * @param $httpRespCode int HTTP response code
1217 * @param $extradata array Data to add to the "<error>" element; array in ApiResult format
1218 * @throws UsageException
1220 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1221 Profiler
::instance()->close();
1222 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1226 * Array that maps message keys to error messages. $1 and friends are replaced.
1228 public static $messageMap = array(
1229 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1230 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1231 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1233 // Messages from Title::getUserPermissionsErrors()
1234 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1235 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1236 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1237 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1238 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1239 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1240 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1241 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1242 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1243 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1244 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1245 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1246 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1247 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1248 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1249 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your email address before you can edit" ),
1250 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1251 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1253 // Miscellaneous interface messages
1254 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1255 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1256 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1257 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1258 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1259 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1260 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1261 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1262 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1263 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1264 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1265 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1266 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1267 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1268 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1269 // 'badarticleerror' => shouldn't happen
1270 // 'badtitletext' => shouldn't happen
1271 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1272 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1273 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1274 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1275 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1276 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1277 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', '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." ),
1278 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1279 'mailnologin' => array( 'code' => 'cantsend', '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" ),
1280 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1281 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1282 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1283 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending email" ),
1284 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1285 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" ),
1286 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1287 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1288 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1289 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1290 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1291 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1292 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1293 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1294 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1295 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1296 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1298 // API-specific messages
1299 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1300 'writedisabled' => array( 'code' => 'noapiwrite', 'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file" ),
1301 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1302 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1303 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1304 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1305 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1306 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1307 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1308 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1309 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1310 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1311 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1312 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1313 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1314 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending email through the wiki" ),
1315 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1316 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1317 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1318 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1319 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1320 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1321 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1322 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1323 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1324 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1325 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1326 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1327 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1328 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1329 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1330 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1331 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1332 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1333 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1334 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1335 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1336 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1337 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1338 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1339 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1340 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1341 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1342 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1343 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1344 'fileexists-shared-forbidden' => array( 'code' => 'fileexists-shared-forbidden', 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' ),
1345 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1347 // ApiEditPage messages
1348 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1349 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1350 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1351 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1352 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1353 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1354 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1355 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1356 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1357 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1358 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1359 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1360 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1361 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1363 // Messages from WikiPage::doEit()
1364 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1365 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1366 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1367 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1370 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1371 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1372 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ),
1373 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1374 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1376 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1377 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1378 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1379 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1381 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1385 * Helper function for readonly errors
1387 public function dieReadOnly() {
1388 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1389 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1390 array( 'readonlyreason' => wfReadOnlyReason() ) );
1394 * Output the error message related to a certain array
1395 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1397 public function dieUsageMsg( $error ) {
1398 # most of the time we send a 1 element, so we might as well send it as
1399 # a string and make this an array here.
1400 if( is_string( $error ) ) {
1401 $error = array( $error );
1403 $parsed = $this->parseMsg( $error );
1404 $this->dieUsage( $parsed['info'], $parsed['code'] );
1408 * Will only set a warning instead of failing if the global $wgDebugAPI
1409 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1410 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1413 public function dieUsageMsgOrDebug( $error ) {
1415 if( $wgDebugAPI !== true ) {
1416 $this->dieUsageMsg( $error );
1418 if( is_string( $error ) ) {
1419 $error = array( $error );
1421 $parsed = $this->parseMsg( $error );
1422 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1423 . ' - ' . $parsed['info'] );
1428 * Die with the $prefix.'badcontinue' error. This call is common enough to make it into the base method.
1429 * @param $condition boolean will only die if this value is true
1432 protected function dieContinueUsageIf( $condition ) {
1435 'Invalid continue param. You should pass the original value returned by the previous query',
1441 * Return the error message related to a certain array
1442 * @param $error array Element of a getUserPermissionsErrors()-style array
1443 * @return array('code' => code, 'info' => info)
1445 public function parseMsg( $error ) {
1446 $error = (array)$error; // It seems strings sometimes make their way in here
1447 $key = array_shift( $error );
1449 // Check whether the error array was nested
1450 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1451 if( is_array( $key ) ) {
1453 $key = array_shift( $error );
1456 if ( isset( self
::$messageMap[$key] ) ) {
1458 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1459 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1463 // If the key isn't present, throw an "unknown error"
1464 return $this->parseMsg( array( 'unknownerror', $key ) );
1468 * Internal code errors should be reported with this method
1469 * @param $method string Method or function name
1470 * @param $message string Error message
1472 protected static function dieDebug( $method, $message ) {
1473 wfDebugDieBacktrace( "Internal error in $method: $message" );
1477 * Indicates if this module needs maxlag to be checked
1480 public function shouldCheckMaxlag() {
1485 * Indicates whether this module requires read rights
1488 public function isReadMode() {
1492 * Indicates whether this module requires write mode
1495 public function isWriteMode() {
1500 * Indicates whether this module must be called with a POST request
1503 public function mustBePosted() {
1508 * Returns whether this module requires a token to execute
1509 * It is used to show possible errors in action=paraminfo
1513 public function needsToken() {
1518 * Returns the token salt if there is one,
1519 * '' if the module doesn't require a salt,
1520 * else false if the module doesn't need a token
1521 * You have also to override needsToken()
1522 * Value is passed to User::getEditToken
1523 * @return bool|string|array
1525 public function getTokenSalt() {
1530 * Gets the user for whom to get the watchlist
1532 * @param $params array
1535 public function getWatchlistUser( $params ) {
1536 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1537 $user = User
::newFromName( $params['owner'], false );
1538 if ( !($user && $user->getId()) ) {
1539 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1541 $token = $user->getOption( 'watchlisttoken' );
1542 if ( $token == '' ||
$token != $params['token'] ) {
1543 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1546 if ( !$this->getUser()->isLoggedIn() ) {
1547 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1549 $user = $this->getUser();
1555 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1557 public function getHelpUrls() {
1562 * Returns a list of all possible errors returned by the module
1563 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1565 public function getPossibleErrors() {
1568 $params = $this->getFinalParams();
1570 foreach ( $params as $paramName => $paramSettings ) {
1571 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) ) {
1572 $ret[] = array( 'missingparam', $paramName );
1575 if ( array_key_exists( 'continue', $params ) ) {
1578 'code' => 'badcontinue',
1579 'info' => 'Invalid continue param. You should pass the original value returned by the previous query'
1584 if ( $this->mustBePosted() ) {
1585 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1588 if ( $this->isReadMode() ) {
1589 $ret[] = array( 'readrequired' );
1592 if ( $this->isWriteMode() ) {
1593 $ret[] = array( 'writerequired' );
1594 $ret[] = array( 'writedisabled' );
1597 if ( $this->needsToken() ) {
1598 $ret[] = array( 'missingparam', 'token' );
1599 $ret[] = array( 'sessionfailure' );
1606 * Parses a list of errors into a standardised format
1607 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1608 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1610 public function parseErrors( $errors ) {
1613 foreach ( $errors as $row ) {
1614 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1617 $ret[] = $this->parseMsg( $row );
1624 * Profiling: total module execution time
1626 private $mTimeIn = 0, $mModuleTime = 0;
1629 * Start module profiling
1631 public function profileIn() {
1632 if ( $this->mTimeIn
!== 0 ) {
1633 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1635 $this->mTimeIn
= microtime( true );
1636 wfProfileIn( $this->getModuleProfileName() );
1640 * End module profiling
1642 public function profileOut() {
1643 if ( $this->mTimeIn
=== 0 ) {
1644 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1646 if ( $this->mDBTimeIn
!== 0 ) {
1647 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1650 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1652 wfProfileOut( $this->getModuleProfileName() );
1656 * When modules crash, sometimes it is needed to do a profileOut() regardless
1657 * of the profiling state the module was in. This method does such cleanup.
1659 public function safeProfileOut() {
1660 if ( $this->mTimeIn
!== 0 ) {
1661 if ( $this->mDBTimeIn
!== 0 ) {
1662 $this->profileDBOut();
1664 $this->profileOut();
1669 * Total time the module was executed
1672 public function getProfileTime() {
1673 if ( $this->mTimeIn
!== 0 ) {
1674 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1676 return $this->mModuleTime
;
1680 * Profiling: database execution time
1682 private $mDBTimeIn = 0, $mDBTime = 0;
1685 * Start module profiling
1687 public function profileDBIn() {
1688 if ( $this->mTimeIn
=== 0 ) {
1689 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1691 if ( $this->mDBTimeIn
!== 0 ) {
1692 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1694 $this->mDBTimeIn
= microtime( true );
1695 wfProfileIn( $this->getModuleProfileName( true ) );
1699 * End database profiling
1701 public function profileDBOut() {
1702 if ( $this->mTimeIn
=== 0 ) {
1703 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1705 if ( $this->mDBTimeIn
=== 0 ) {
1706 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1709 $time = microtime( true ) - $this->mDBTimeIn
;
1710 $this->mDBTimeIn
= 0;
1712 $this->mDBTime +
= $time;
1713 $this->getMain()->mDBTime +
= $time;
1714 wfProfileOut( $this->getModuleProfileName( true ) );
1718 * Total time the module used the database
1721 public function getProfileDBTime() {
1722 if ( $this->mDBTimeIn
!== 0 ) {
1723 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1725 return $this->mDBTime
;
1729 * Gets a default slave database connection object
1730 * @return DatabaseBase
1732 protected function getDB() {
1733 if ( !isset( $this->mSlaveDB
) ) {
1734 $this->profileDBIn();
1735 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
1736 $this->profileDBOut();
1738 return $this->mSlaveDB
;
1742 * Debugging function that prints a value and an optional backtrace
1743 * @param $value mixed Value to print
1744 * @param $name string Description of the printed value
1745 * @param $backtrace bool If true, print a backtrace
1747 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1748 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1749 var_export( $value );
1751 print "\n" . wfBacktrace();