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
;
140 * Get the module manager, or null if this module has no sub-modules
142 * @return ApiModuleManager
144 public function getModuleManager() {
149 * Get parameter prefix (usually two letters or an empty string).
152 public function getModulePrefix() {
153 return $this->mModulePrefix
;
157 * Get the name of the module as shown in the profiler log
159 * @param $db DatabaseBase|bool
163 public function getModuleProfileName( $db = false ) {
165 return 'API:' . $this->mModuleName
. '-DB';
167 return 'API:' . $this->mModuleName
;
172 * Get the main module
173 * @return ApiMain object
175 public function getMain() {
176 return $this->mMainModule
;
180 * Returns true if this module is the main module ($this === $this->mMainModule),
184 public function isMain() {
185 return $this === $this->mMainModule
;
189 * Get the result object
192 public function getResult() {
193 // Main module has getResult() method overriden
194 // Safety - avoid infinite loop:
195 if ( $this->isMain() ) {
196 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
198 return $this->getMain()->getResult();
202 * Get the result data array (read-only)
205 public function getResultData() {
206 return $this->getResult()->getData();
210 * Create a new RequestContext object to use e.g. for calls to other parts
212 * The object will have the WebRequest and the User object set to the ones
213 * used in this instance.
215 * @deprecated since 1.19 use getContext to get the current context
216 * @return DerivativeContext
218 public function createContext() {
219 wfDeprecated( __METHOD__
, '1.19' );
220 return new DerivativeContext( $this->getContext() );
224 * Set warning section for this module. Users should monitor this
225 * section to notice any changes in API. Multiple calls to this
226 * function will result in the warning messages being separated by
228 * @param $warning string Warning message
230 public function setWarning( $warning ) {
231 $result = $this->getResult();
232 $data = $result->getData();
233 $moduleName = $this->getModuleName();
234 if ( isset( $data['warnings'][$moduleName] ) ) {
235 // Don't add duplicate warnings
236 $oldWarning = $data['warnings'][$moduleName]['*'];
237 $warnPos = strpos( $oldWarning, $warning );
238 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
239 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
240 // Check if $warning is followed by "\n" or the end of the $oldWarning
241 $warnPos +
= strlen( $warning );
242 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
246 // If there is a warning already, append it to the existing one
247 $warning = "$oldWarning\n$warning";
250 ApiResult
::setContent( $msg, $warning );
251 $result->disableSizeCheck();
252 $result->addValue( 'warnings', $moduleName,
253 $msg, ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP
);
254 $result->enableSizeCheck();
258 * If the module may only be used with a certain format module,
259 * it should override this method to return an instance of that formatter.
260 * A value of null means the default format will be used.
261 * @return mixed instance of a derived class of ApiFormatBase, or null
263 public function getCustomPrinter() {
268 * Generates help message for this module, or false if there is no description
269 * @return mixed string or false
271 public function makeHelpMsg() {
272 static $lnPrfx = "\n ";
274 $msg = $this->getFinalDescription();
276 if ( $msg !== false ) {
278 if ( !is_array( $msg ) ) {
283 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
285 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
287 if ( $this->isReadMode() ) {
288 $msg .= "\nThis module requires read rights";
290 if ( $this->isWriteMode() ) {
291 $msg .= "\nThis module requires write rights";
293 if ( $this->mustBePosted() ) {
294 $msg .= "\nThis module only accepts POST requests";
296 if ( $this->isReadMode() ||
$this->isWriteMode() ||
297 $this->mustBePosted() ) {
302 $paramsMsg = $this->makeHelpMsgParameters();
303 if ( $paramsMsg !== false ) {
304 $msg .= "Parameters:\n$paramsMsg";
307 $examples = $this->getExamples();
308 if ( $examples !== false && $examples !== '' ) {
309 if ( !is_array( $examples ) ) {
314 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
315 foreach( $examples as $k => $v ) {
317 if ( is_numeric( $k ) ) {
320 if ( is_array( $v ) ) {
321 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
326 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
336 * @param $item string
339 private function indentExampleText( $item ) {
344 * @param $prefix string Text to split output items
345 * @param $title string What is being output
346 * @param $input string|array
349 protected function makeHelpArrayToString( $prefix, $title, $input ) {
350 if ( $input === false ) {
353 if ( !is_array( $input ) ) {
354 $input = array( $input );
357 if ( count( $input ) > 0 ) {
359 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
363 $msg .= implode( $prefix, $input ) . "\n";
370 * Generates the parameter descriptions for this module, to be displayed in the
372 * @return string or false
374 public function makeHelpMsgParameters() {
375 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
378 $paramsDescription = $this->getFinalParamDescription();
380 $paramPrefix = "\n" . str_repeat( ' ', 24 );
381 $descWordwrap = "\n" . str_repeat( ' ', 28 );
382 foreach ( $params as $paramName => $paramSettings ) {
383 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
384 if ( is_array( $desc ) ) {
385 $desc = implode( $paramPrefix, $desc );
389 if ( !is_array( $paramSettings ) ) {
390 $paramSettings = array(
391 self
::PARAM_DFLT
=> $paramSettings,
395 //handle missing type
396 if ( !isset( $paramSettings[ApiBase
::PARAM_TYPE
] ) ) {
397 $dflt = isset( $paramSettings[ApiBase
::PARAM_DFLT
] ) ?
$paramSettings[ApiBase
::PARAM_DFLT
] : null;
398 if ( is_bool( $dflt ) ) {
399 $paramSettings[ApiBase
::PARAM_TYPE
] = 'boolean';
400 } elseif ( is_string( $dflt ) ||
is_null( $dflt ) ) {
401 $paramSettings[ApiBase
::PARAM_TYPE
] = 'string';
402 } elseif ( is_int( $dflt ) ) {
403 $paramSettings[ApiBase
::PARAM_TYPE
] = 'integer';
407 if ( isset( $paramSettings[self
::PARAM_DEPRECATED
] ) && $paramSettings[self
::PARAM_DEPRECATED
] ) {
408 $desc = "DEPRECATED! $desc";
411 if ( isset( $paramSettings[self
::PARAM_REQUIRED
] ) && $paramSettings[self
::PARAM_REQUIRED
] ) {
412 $desc .= $paramPrefix . "This parameter is required";
415 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
416 if ( isset( $type ) ) {
417 $hintPipeSeparated = true;
418 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
420 $prompt = 'Values (separate with \'|\'): ';
422 $prompt = 'One value: ';
425 if ( is_array( $type ) ) {
428 foreach ( $type as $t ) {
430 $nothingPrompt = 'Can be empty, or ';
435 $desc .= $paramPrefix . $nothingPrompt . $prompt;
436 $choicesstring = implode( ', ', $choices );
437 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
438 $hintPipeSeparated = false;
442 // Special handling because namespaces are type-limited, yet they are not given
443 $desc .= $paramPrefix . $prompt;
444 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
445 100, $descWordwrap );
446 $hintPipeSeparated = false;
449 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
450 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
451 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
456 $s = $multi ?
's' : '';
457 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
458 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
459 if ( $hasMin ||
$hasMax ) {
461 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
462 } elseif ( !$hasMin ) {
463 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
465 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
468 $desc .= $paramPrefix . $intRangeStr;
475 if ( $hintPipeSeparated ) {
476 $desc .= $paramPrefix . "Separate values with '|'";
479 $isArray = is_array( $type );
481 ||
$isArray && count( $type ) > self
::LIMIT_SML1
) {
482 $desc .= $paramPrefix . "Maximum number of values " .
483 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
488 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
489 if ( !is_null( $default ) && $default !== false ) {
490 $desc .= $paramPrefix . "Default: $default";
493 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
503 * Returns the description string for this module
504 * @return mixed string or array of strings
506 protected function getDescription() {
511 * Returns usage examples for this module. Return false if no examples are available.
512 * @return bool|string|array
514 protected function getExamples() {
519 * Returns an array of allowed parameters (parameter name) => (default
520 * value) or (parameter name) => (array with PARAM_* constants as keys)
521 * Don't call this function directly: use getFinalParams() to allow
522 * hooks to modify parameters as needed.
524 * Some derived classes may choose to handle an integer $flags parameter
525 * in the overriding methods. Callers of this method can pass zero or
526 * more OR-ed flags like GET_VALUES_FOR_HELP.
530 protected function getAllowedParams( /* $flags = 0 */ ) {
531 // int $flags is not declared because it causes "Strict standards"
532 // warning. Most derived classes do not implement it.
537 * Returns an array of parameter descriptions.
538 * Don't call this function directly: use getFinalParamDescription() to
539 * allow hooks to modify descriptions as needed.
540 * @return array|bool False on no parameter descriptions
542 protected function getParamDescription() {
547 * Get final list of parameters, after hooks have had a chance to
548 * tweak it as needed.
550 * @param $flags int Zero or more flags like GET_VALUES_FOR_HELP
551 * @return array|Bool False on no parameters
552 * @since 1.21 $flags param added
554 public function getFinalParams( $flags = 0 ) {
555 $params = $this->getAllowedParams( $flags );
556 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
561 * Get final parameter descriptions, after hooks have had a chance to tweak it as
564 * @return array|bool False on no parameter descriptions
566 public function getFinalParamDescription() {
567 $desc = $this->getParamDescription();
568 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
573 * Returns possible properties in the result, grouped by the value of the prop parameter
576 * Properties that are shown always are in a group with empty string as a key.
577 * Properties that can be shown by several values of prop are included multiple times.
578 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
579 * those on the root object are under the key PROP_ROOT.
580 * The array can also contain a boolean under the key PROP_LIST,
581 * indicating whether the result is a list.
583 * Don't call this functon directly: use getFinalResultProperties() to
584 * allow hooks to modify descriptions as needed.
586 * @return array|bool False on no properties
588 protected function getResultProperties() {
593 * Get final possible result properties, after hooks have had a chance to tweak it as
598 public function getFinalResultProperties() {
599 $properties = $this->getResultProperties();
600 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
605 * Add token properties to the array used by getResultProperties,
606 * based on a token functions mapping.
608 protected static function addTokenProperties( &$props, $tokenFunctions ) {
609 foreach ( array_keys( $tokenFunctions ) as $token ) {
610 $props[''][$token . 'token'] = array(
611 ApiBase
::PROP_TYPE
=> 'string',
612 ApiBase
::PROP_NULLABLE
=> true
618 * Get final module description, after hooks have had a chance to tweak it as
621 * @return array|bool False on no parameters
623 public function getFinalDescription() {
624 $desc = $this->getDescription();
625 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
630 * This method mangles parameter name based on the prefix supplied to the constructor.
631 * Override this method to change parameter name during runtime
632 * @param $paramName string Parameter name
633 * @return string Prefixed parameter name
635 public function encodeParamName( $paramName ) {
636 return $this->mModulePrefix
. $paramName;
640 * Using getAllowedParams(), this function makes an array of the values
641 * provided by the user, with key being the name of the variable, and
642 * value - validated value from user or default. limits will not be
643 * parsed if $parseLimit is set to false; use this when the max
644 * limit is not definitive yet, e.g. when getting revisions.
645 * @param $parseLimit Boolean: true by default
648 public function extractRequestParams( $parseLimit = true ) {
649 // Cache parameters, for performance and to avoid bug 24564.
650 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
651 $params = $this->getFinalParams();
654 if ( $params ) { // getFinalParams() can return false
655 foreach ( $params as $paramName => $paramSettings ) {
656 $results[$paramName] = $this->getParameterFromSettings(
657 $paramName, $paramSettings, $parseLimit );
660 $this->mParamCache
[$parseLimit] = $results;
662 return $this->mParamCache
[$parseLimit];
666 * Get a value for the given parameter
667 * @param $paramName string Parameter name
668 * @param $parseLimit bool see extractRequestParams()
669 * @return mixed Parameter value
671 protected function getParameter( $paramName, $parseLimit = true ) {
672 $params = $this->getFinalParams();
673 $paramSettings = $params[$paramName];
674 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
678 * Die if none or more than one of a certain set of parameters is set and not false.
679 * @param $params array of parameter names
681 public function requireOnlyOneParameter( $params ) {
682 $required = func_get_args();
683 array_shift( $required );
684 $p = $this->getModulePrefix();
686 $intersection = array_intersect( array_keys( array_filter( $params,
687 array( $this, "parameterNotEmpty" ) ) ), $required );
689 if ( count( $intersection ) > 1 ) {
690 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
691 } elseif ( count( $intersection ) == 0 ) {
692 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
697 * Generates the possible errors requireOnlyOneParameter() can die with
699 * @param $params array
702 public function getRequireOnlyOneParameterErrorMessages( $params ) {
703 $p = $this->getModulePrefix();
704 $params = implode( ", {$p}", $params );
707 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
708 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
713 * Die if more than one of a certain set of parameters is set and not false.
715 * @param $params array
717 public function requireMaxOneParameter( $params ) {
718 $required = func_get_args();
719 array_shift( $required );
720 $p = $this->getModulePrefix();
722 $intersection = array_intersect( array_keys( array_filter( $params,
723 array( $this, "parameterNotEmpty" ) ) ), $required );
725 if ( count( $intersection ) > 1 ) {
726 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
731 * Generates the possible error requireMaxOneParameter() can die with
733 * @param $params array
736 public function getRequireMaxOneParameterErrorMessages( $params ) {
737 $p = $this->getModulePrefix();
738 $params = implode( ", {$p}", $params );
741 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
746 * @param $params array
747 * @param $load bool|string Whether load the object's state from the database:
748 * - false: don't load (if the pageid is given, it will still be loaded)
749 * - 'fromdb': load from a slave database
750 * - 'fromdbmaster': load from the master database
753 public function getTitleOrPageId( $params, $load = false ) {
754 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
757 if ( isset( $params['title'] ) ) {
758 $titleObj = Title
::newFromText( $params['title'] );
760 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
762 if ( !$titleObj->canExist() ) {
763 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
765 $pageObj = WikiPage
::factory( $titleObj );
766 if ( $load !== false ) {
767 $pageObj->loadPageData( $load );
769 } elseif ( isset( $params['pageid'] ) ) {
770 if ( $load === false ) {
773 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
775 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
785 public function getTitleOrPageIdErrorMessage() {
787 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
789 array( 'invalidtitle', 'title' ),
790 array( 'nosuchpageid', 'pageid' ),
796 * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set
798 * @param $x object Parameter to check is not null/false
801 private function parameterNotEmpty( $x ) {
802 return !is_null( $x ) && $x !== false;
806 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
810 public static function getValidNamespaces() {
811 wfDeprecated( __METHOD__
, '1.17' );
812 return MWNamespace
::getValidNamespaces();
816 * Return true if we're to watch the page, false if not, null if no change.
817 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
818 * @param $titleObj Title the page under consideration
819 * @param $userOption String The user option to consider when $watchlist=preferences.
820 * If not set will magically default to either watchdefault or watchcreations
823 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
825 $userWatching = $this->getUser()->isWatched( $titleObj );
827 switch ( $watchlist ) {
835 # If the user is already watching, don't bother checking
836 if ( $userWatching ) {
839 # If no user option was passed, use watchdefault or watchcreation
840 if ( is_null( $userOption ) ) {
841 $userOption = $titleObj->exists()
842 ?
'watchdefault' : 'watchcreations';
844 # Watch the article based on the user preference
845 return (bool)$this->getUser()->getOption( $userOption );
848 return $userWatching;
851 return $userWatching;
856 * Set a watch (or unwatch) based the based on a watchlist parameter.
857 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
858 * @param $titleObj Title the article's title to change
859 * @param $userOption String The user option to consider when $watch=preferences
861 protected function setWatch( $watch, $titleObj, $userOption = null ) {
862 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
863 if ( $value === null ) {
867 $user = $this->getUser();
869 WatchAction
::doWatch( $titleObj, $user );
871 WatchAction
::doUnwatch( $titleObj, $user );
876 * Using the settings determine the value for the given parameter
878 * @param $paramName String: parameter name
879 * @param $paramSettings array|mixed default value or an array of settings
880 * using PARAM_* constants.
881 * @param $parseLimit Boolean: parse limit?
882 * @return mixed Parameter value
884 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
885 // Some classes may decide to change parameter names
886 $encParamName = $this->encodeParamName( $paramName );
888 if ( !is_array( $paramSettings ) ) {
889 $default = $paramSettings;
891 $type = gettype( $paramSettings );
896 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
897 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
898 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
899 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
900 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
901 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
903 // When type is not given, and no choices, the type is the same as $default
904 if ( !isset( $type ) ) {
905 if ( isset( $default ) ) {
906 $type = gettype( $default );
908 $type = 'NULL'; // allow everything
913 if ( $type == 'boolean' ) {
914 if ( isset( $default ) && $default !== false ) {
915 // Having a default value of anything other than 'false' is not allowed
916 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
919 $value = $this->getMain()->getCheck( $encParamName );
921 $value = $this->getMain()->getVal( $encParamName, $default );
923 if ( isset( $value ) && $type == 'namespace' ) {
924 $type = MWNamespace
::getValidNamespaces();
928 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
929 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
932 // More validation only when choices were not given
933 // choices were validated in parseMultiValue()
934 if ( isset( $value ) ) {
935 if ( !is_array( $type ) ) {
937 case 'NULL': // nothing to do
940 if ( $required && $value === '' ) {
941 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
945 case 'integer': // Force everything using intval() and optionally validate limits
946 $min = isset ( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
947 $max = isset ( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
948 $enforceLimits = isset ( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
949 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
951 if ( is_array( $value ) ) {
952 $value = array_map( 'intval', $value );
953 if ( !is_null( $min ) ||
!is_null( $max ) ) {
954 foreach ( $value as &$v ) {
955 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
959 $value = intval( $value );
960 if ( !is_null( $min ) ||
!is_null( $max ) ) {
961 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
966 if ( !$parseLimit ) {
967 // Don't do any validation whatsoever
970 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
971 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
974 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
976 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
977 if ( $value == 'max' ) {
978 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
979 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
981 $value = intval( $value );
982 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
987 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
991 if ( is_array( $value ) ) {
992 foreach ( $value as $key => $val ) {
993 $value[$key] = $this->validateTimestamp( $val, $encParamName );
996 $value = $this->validateTimestamp( $value, $encParamName );
1000 if ( !is_array( $value ) ) {
1001 $value = array( $value );
1004 foreach ( $value as $key => $val ) {
1005 $title = Title
::makeTitleSafe( NS_USER
, $val );
1006 if ( is_null( $title ) ) {
1007 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
1009 $value[$key] = $title->getText();
1017 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1021 // Throw out duplicates if requested
1022 if ( is_array( $value ) && !$dupes ) {
1023 $value = array_unique( $value );
1026 // Set a warning if a deprecated parameter has been passed
1027 if ( $deprecated && $value !== false ) {
1028 $this->setWarning( "The $encParamName parameter has been deprecated." );
1030 } elseif ( $required ) {
1031 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1038 * Return an array of values that were given in a 'a|b|c' notation,
1039 * after it optionally validates them against the list allowed values.
1041 * @param $valueName string The name of the parameter (for error
1043 * @param $value mixed The value being parsed
1044 * @param $allowMultiple bool Can $value contain more than one value
1046 * @param $allowedValues mixed An array of values to check against. If
1047 * null, all values are accepted.
1048 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1050 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1051 if ( trim( $value ) === '' && $allowMultiple ) {
1055 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1056 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
1057 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
1058 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
1060 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1061 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1064 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1065 // Bug 33482 - Allow entries with | in them for non-multiple values
1066 if ( in_array( $value, $allowedValues ) ) {
1070 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
1071 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1074 if ( is_array( $allowedValues ) ) {
1075 // Check for unknown values
1076 $unknown = array_diff( $valuesList, $allowedValues );
1077 if ( count( $unknown ) ) {
1078 if ( $allowMultiple ) {
1079 $s = count( $unknown ) > 1 ?
's' : '';
1080 $vals = implode( ", ", $unknown );
1081 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1083 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1086 // Now throw them out
1087 $valuesList = array_intersect( $valuesList, $allowedValues );
1090 return $allowMultiple ?
$valuesList : $valuesList[0];
1094 * Validate the value against the minimum and user/bot maximum limits.
1095 * Prints usage info on failure.
1096 * @param $paramName string Parameter name
1097 * @param $value int Parameter value
1098 * @param $min int|null Minimum value
1099 * @param $max int|null Maximum value for users
1100 * @param $botMax int Maximum value for sysops/bots
1101 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1103 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1104 if ( !is_null( $min ) && $value < $min ) {
1106 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1107 $this->warnOrDie( $msg, $enforceLimits );
1111 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1112 if ( $this->getMain()->isInternalMode() ) {
1116 // Optimization: do not check user's bot status unless really needed -- skips db query
1117 // assumes $botMax >= $max
1118 if ( !is_null( $max ) && $value > $max ) {
1119 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1120 if ( $value > $botMax ) {
1121 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1122 $this->warnOrDie( $msg, $enforceLimits );
1126 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1127 $this->warnOrDie( $msg, $enforceLimits );
1134 * @param $value string
1135 * @param $paramName string
1138 function validateTimestamp( $value, $paramName ) {
1139 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1140 if ( $unixTimestamp === false ) {
1141 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
1143 return wfTimestamp( TS_MW
, $unixTimestamp );
1147 * Adds a warning to the output, else dies
1149 * @param $msg String Message to show as a warning, or error message if dying
1150 * @param $enforceLimits Boolean Whether this is an enforce (die)
1152 private function warnOrDie( $msg, $enforceLimits = false ) {
1153 if ( $enforceLimits ) {
1154 $this->dieUsage( $msg, 'integeroutofrange' );
1156 $this->setWarning( $msg );
1161 * Truncate an array to a certain length.
1162 * @param $arr array Array to truncate
1163 * @param $limit int Maximum length
1164 * @return bool True if the array was truncated, false otherwise
1166 public static function truncateArray( &$arr, $limit ) {
1168 while ( count( $arr ) > $limit ) {
1176 * Throw a UsageException, which will (if uncaught) call the main module's
1177 * error handler and die with an error message.
1179 * @param $description string One-line human-readable description of the
1180 * error condition, e.g., "The API requires a valid action parameter"
1181 * @param $errorCode string Brief, arbitrary, stable string to allow easy
1182 * automated identification of the error, e.g., 'unknown_action'
1183 * @param $httpRespCode int HTTP response code
1184 * @param $extradata array Data to add to the "<error>" element; array in ApiResult format
1185 * @throws UsageException
1187 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1188 Profiler
::instance()->close();
1189 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1193 * Array that maps message keys to error messages. $1 and friends are replaced.
1195 public static $messageMap = array(
1196 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1197 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1198 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1200 // Messages from Title::getUserPermissionsErrors()
1201 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1202 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1203 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1204 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1205 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1206 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1207 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1208 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1209 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1210 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1211 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1212 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1213 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1214 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1215 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1216 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
1217 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1218 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1220 // Miscellaneous interface messages
1221 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1222 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1223 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1224 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1225 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1226 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1227 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1228 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1229 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1230 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1231 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1232 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1233 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1234 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1235 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1236 // 'badarticleerror' => shouldn't happen
1237 // 'badtitletext' => shouldn't happen
1238 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1239 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1240 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1241 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1242 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1243 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1244 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP invidually, but you can unblock the range as a whole." ),
1245 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1246 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed e-mail address, or you are not allowed to send e-mail to other users, so you cannot send e-mail" ),
1247 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1248 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1249 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1250 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
1251 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1252 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users" ),
1253 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1254 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1255 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1256 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1257 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1258 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1259 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1260 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1261 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1262 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1263 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1265 // API-specific messages
1266 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1267 '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" ),
1268 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1269 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1270 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1271 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1272 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1273 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1274 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1275 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1276 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1277 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1278 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1279 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1280 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1281 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
1282 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1283 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1284 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1285 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1286 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1287 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1288 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1289 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1290 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1291 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1292 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1293 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1294 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1295 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1296 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1297 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1298 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1299 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1300 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1301 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1302 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1303 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1304 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1305 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1306 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1307 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1308 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1309 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1310 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1311 '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.' ),
1312 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1314 // ApiEditPage messages
1315 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1316 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1317 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1318 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1319 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1320 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1321 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1322 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1323 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1324 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1325 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1326 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1327 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1328 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1330 // Messages from WikiPage::doEit()
1331 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1332 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1333 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1334 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1337 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1338 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1339 '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' ),
1340 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1341 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1343 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1344 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1345 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1346 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1348 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1352 * Helper function for readonly errors
1354 public function dieReadOnly() {
1355 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1356 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1357 array( 'readonlyreason' => wfReadOnlyReason() ) );
1361 * Output the error message related to a certain array
1362 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1364 public function dieUsageMsg( $error ) {
1365 # most of the time we send a 1 element, so we might as well send it as
1366 # a string and make this an array here.
1367 if( is_string( $error ) ) {
1368 $error = array( $error );
1370 $parsed = $this->parseMsg( $error );
1371 $this->dieUsage( $parsed['info'], $parsed['code'] );
1375 * Will only set a warning instead of failing if the global $wgDebugAPI
1376 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1377 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1380 public function dieUsageMsgOrDebug( $error ) {
1382 if( $wgDebugAPI !== true ) {
1383 $this->dieUsageMsg( $error );
1385 if( is_string( $error ) ) {
1386 $error = array( $error );
1388 $parsed = $this->parseMsg( $error );
1389 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1390 . ' - ' . $parsed['info'] );
1395 * Return the error message related to a certain array
1396 * @param $error array Element of a getUserPermissionsErrors()-style array
1397 * @return array('code' => code, 'info' => info)
1399 public function parseMsg( $error ) {
1400 $error = (array)$error; // It seems strings sometimes make their way in here
1401 $key = array_shift( $error );
1403 // Check whether the error array was nested
1404 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1405 if( is_array( $key ) ) {
1407 $key = array_shift( $error );
1410 if ( isset( self
::$messageMap[$key] ) ) {
1412 'code' => wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1413 'info' => wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1417 // If the key isn't present, throw an "unknown error"
1418 return $this->parseMsg( array( 'unknownerror', $key ) );
1422 * Internal code errors should be reported with this method
1423 * @param $method string Method or function name
1424 * @param $message string Error message
1426 protected static function dieDebug( $method, $message ) {
1427 wfDebugDieBacktrace( "Internal error in $method: $message" );
1431 * Indicates if this module needs maxlag to be checked
1434 public function shouldCheckMaxlag() {
1439 * Indicates whether this module requires read rights
1442 public function isReadMode() {
1446 * Indicates whether this module requires write mode
1449 public function isWriteMode() {
1454 * Indicates whether this module must be called with a POST request
1457 public function mustBePosted() {
1462 * Returns whether this module requires a token to execute
1463 * It is used to show possible errors in action=paraminfo
1467 public function needsToken() {
1472 * Returns the token salt if there is one,
1473 * '' if the module doesn't require a salt,
1474 * else false if the module doesn't need a token
1475 * You have also to override needsToken()
1476 * Value is passed to User::getEditToken
1477 * @return bool|string|array
1479 public function getTokenSalt() {
1484 * Gets the user for whom to get the watchlist
1486 * @param $params array
1489 public function getWatchlistUser( $params ) {
1490 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1491 $user = User
::newFromName( $params['owner'], false );
1492 if ( !($user && $user->getId()) ) {
1493 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1495 $token = $user->getOption( 'watchlisttoken' );
1496 if ( $token == '' ||
$token != $params['token'] ) {
1497 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1500 if ( !$this->getUser()->isLoggedIn() ) {
1501 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1503 $user = $this->getUser();
1509 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1511 public function getHelpUrls() {
1516 * Returns a list of all possible errors returned by the module
1517 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1519 public function getPossibleErrors() {
1522 $params = $this->getFinalParams();
1524 foreach ( $params as $paramName => $paramSettings ) {
1525 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) ) {
1526 $ret[] = array( 'missingparam', $paramName );
1531 if ( $this->mustBePosted() ) {
1532 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1535 if ( $this->isReadMode() ) {
1536 $ret[] = array( 'readrequired' );
1539 if ( $this->isWriteMode() ) {
1540 $ret[] = array( 'writerequired' );
1541 $ret[] = array( 'writedisabled' );
1544 if ( $this->needsToken() ) {
1545 $ret[] = array( 'missingparam', 'token' );
1546 $ret[] = array( 'sessionfailure' );
1553 * Parses a list of errors into a standardised format
1554 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1555 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1557 public function parseErrors( $errors ) {
1560 foreach ( $errors as $row ) {
1561 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1564 $ret[] = $this->parseMsg( $row );
1571 * Profiling: total module execution time
1573 private $mTimeIn = 0, $mModuleTime = 0;
1576 * Start module profiling
1578 public function profileIn() {
1579 if ( $this->mTimeIn
!== 0 ) {
1580 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1582 $this->mTimeIn
= microtime( true );
1583 wfProfileIn( $this->getModuleProfileName() );
1587 * End module profiling
1589 public function profileOut() {
1590 if ( $this->mTimeIn
=== 0 ) {
1591 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1593 if ( $this->mDBTimeIn
!== 0 ) {
1594 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1597 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1599 wfProfileOut( $this->getModuleProfileName() );
1603 * When modules crash, sometimes it is needed to do a profileOut() regardless
1604 * of the profiling state the module was in. This method does such cleanup.
1606 public function safeProfileOut() {
1607 if ( $this->mTimeIn
!== 0 ) {
1608 if ( $this->mDBTimeIn
!== 0 ) {
1609 $this->profileDBOut();
1611 $this->profileOut();
1616 * Total time the module was executed
1619 public function getProfileTime() {
1620 if ( $this->mTimeIn
!== 0 ) {
1621 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1623 return $this->mModuleTime
;
1627 * Profiling: database execution time
1629 private $mDBTimeIn = 0, $mDBTime = 0;
1632 * Start module profiling
1634 public function profileDBIn() {
1635 if ( $this->mTimeIn
=== 0 ) {
1636 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1638 if ( $this->mDBTimeIn
!== 0 ) {
1639 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1641 $this->mDBTimeIn
= microtime( true );
1642 wfProfileIn( $this->getModuleProfileName( true ) );
1646 * End database profiling
1648 public function profileDBOut() {
1649 if ( $this->mTimeIn
=== 0 ) {
1650 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1652 if ( $this->mDBTimeIn
=== 0 ) {
1653 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1656 $time = microtime( true ) - $this->mDBTimeIn
;
1657 $this->mDBTimeIn
= 0;
1659 $this->mDBTime +
= $time;
1660 $this->getMain()->mDBTime +
= $time;
1661 wfProfileOut( $this->getModuleProfileName( true ) );
1665 * Total time the module used the database
1668 public function getProfileDBTime() {
1669 if ( $this->mDBTimeIn
!== 0 ) {
1670 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1672 return $this->mDBTime
;
1676 * Gets a default slave database connection object
1677 * @return DatabaseBase
1679 protected function getDB() {
1680 if ( !isset( $this->mSlaveDB
) ) {
1681 $this->profileDBIn();
1682 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
1683 $this->profileDBOut();
1685 return $this->mSlaveDB
;
1689 * Debugging function that prints a value and an optional backtrace
1690 * @param $value mixed Value to print
1691 * @param $name string Description of the printed value
1692 * @param $backtrace bool If true, print a backtrace
1694 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1695 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1696 var_export( $value );
1698 print "\n" . wfBacktrace();