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 LIMIT_BIG1
= 500; // Fast query, std user limit
60 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
61 const LIMIT_SML1
= 50; // Slow query, std user limit
62 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
64 private $mMainModule, $mModuleName, $mModulePrefix;
65 private $mParamCache = array();
69 * @param $mainModule ApiMain object
70 * @param $moduleName string Name of this module
71 * @param $modulePrefix string Prefix to use for parameter names
73 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
74 $this->mMainModule
= $mainModule;
75 $this->mModuleName
= $moduleName;
76 $this->mModulePrefix
= $modulePrefix;
78 if ( !$this->isMain() ) {
79 $this->setContext( $mainModule->getContext() );
83 /*****************************************************************************
85 *****************************************************************************/
88 * Evaluates the parameters, performs the requested query, and sets up
89 * the result. Concrete implementations of ApiBase must override this
90 * method to provide whatever functionality their module offers.
91 * Implementations must not produce any output on their own and are not
92 * expected to handle any errors.
94 * The execute() method will be invoked directly by ApiMain immediately
95 * before the result of the module is output. Aside from the
96 * constructor, implementations should assume that no other methods
97 * will be called externally on the module before the result is
100 * The result data should be stored in the ApiResult object available
101 * through getResult().
103 public abstract function execute();
106 * Returns a string that identifies the version of the extending class.
107 * Typically includes the class name, the svn revision, timestamp, and
108 * last author. Usually done with SVN's Id keyword
111 public abstract function getVersion();
114 * Get the name of the module being executed by this instance
117 public function getModuleName() {
118 return $this->mModuleName
;
122 * Get parameter prefix (usually two letters or an empty string).
125 public function getModulePrefix() {
126 return $this->mModulePrefix
;
130 * Get the name of the module as shown in the profiler log
132 * @param $db DatabaseBase
136 public function getModuleProfileName( $db = false ) {
138 return 'API:' . $this->mModuleName
. '-DB';
140 return 'API:' . $this->mModuleName
;
145 * Get the main module
146 * @return ApiMain object
148 public function getMain() {
149 return $this->mMainModule
;
153 * Returns true if this module is the main module ($this === $this->mMainModule),
157 public function isMain() {
158 return $this === $this->mMainModule
;
162 * Get the result object
165 public function getResult() {
166 // Main module has getResult() method overriden
167 // Safety - avoid infinite loop:
168 if ( $this->isMain() ) {
169 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
171 return $this->getMain()->getResult();
175 * Get the result data array (read-only)
178 public function getResultData() {
179 return $this->getResult()->getData();
183 * Create a new RequestContext object to use e.g. for calls to other parts
185 * The object will have the WebRequest and the User object set to the ones
186 * used in this instance.
188 * @deprecated since 1.19 use getContext to get the current context
189 * @return DerivativeContext
191 public function createContext() {
192 wfDeprecated( __METHOD__
, '1.19' );
193 return new DerivativeContext( $this->getContext() );
197 * Set warning section for this module. Users should monitor this
198 * section to notice any changes in API. Multiple calls to this
199 * function will result in the warning messages being separated by
201 * @param $warning string Warning message
203 public function setWarning( $warning ) {
204 $result = $this->getResult();
205 $data = $result->getData();
206 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
207 // Don't add duplicate warnings
208 $warn_regex = preg_quote( $warning, '/' );
209 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
212 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
213 // If there is a warning already, append it to the existing one
214 $warning = "$oldwarning\n$warning";
215 $result->unsetValue( 'warnings', $this->getModuleName() );
218 ApiResult
::setContent( $msg, $warning );
219 $result->disableSizeCheck();
220 $result->addValue( 'warnings', $this->getModuleName(), $msg );
221 $result->enableSizeCheck();
225 * If the module may only be used with a certain format module,
226 * it should override this method to return an instance of that formatter.
227 * A value of null means the default format will be used.
228 * @return mixed instance of a derived class of ApiFormatBase, or null
230 public function getCustomPrinter() {
235 * Generates help message for this module, or false if there is no description
236 * @return mixed string or false
238 public function makeHelpMsg() {
239 static $lnPrfx = "\n ";
241 $msg = $this->getFinalDescription();
243 if ( $msg !== false ) {
245 if ( !is_array( $msg ) ) {
250 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
252 if ( $this->isReadMode() ) {
253 $msg .= "\nThis module requires read rights";
255 if ( $this->isWriteMode() ) {
256 $msg .= "\nThis module requires write rights";
258 if ( $this->mustBePosted() ) {
259 $msg .= "\nThis module only accepts POST requests";
261 if ( $this->isReadMode() ||
$this->isWriteMode() ||
262 $this->mustBePosted() ) {
267 $paramsMsg = $this->makeHelpMsgParameters();
268 if ( $paramsMsg !== false ) {
269 $msg .= "Parameters:\n$paramsMsg";
272 $examples = $this->getExamples();
273 if ( $examples !== false && $examples !== '' ) {
274 if ( !is_array( $examples ) ) {
279 $msg .= "Example" . ( count( $examples ) > 1 ?
's' : '' ) . ":\n";
280 foreach( $examples as $k => $v ) {
282 if ( is_numeric( $k ) ) {
286 if ( is_array( $v ) ) {
287 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
291 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
296 $msg .= $this->makeHelpArrayToString( $lnPrfx, "Help page", $this->getHelpUrls() );
298 if ( $this->getMain()->getShowVersions() ) {
299 $versions = $this->getVersion();
300 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
301 $callback = array( $this, 'makeHelpMsg_callback' );
303 if ( is_array( $versions ) ) {
304 foreach ( $versions as &$v ) {
305 $v = preg_replace_callback( $pattern, $callback, $v );
307 $versions = implode( "\n ", $versions );
309 $versions = preg_replace_callback( $pattern, $callback, $versions );
312 $msg .= "Version:\n $versions\n";
320 * @param $item string
323 private function indentExampleText( $item ) {
328 * @param $prefix string Text to split output items
329 * @param $title string What is being output
330 * @param $input string|array
333 protected function makeHelpArrayToString( $prefix, $title, $input ) {
334 if ( $input === false ) {
337 if ( !is_array( $input ) ) {
343 if ( count( $input ) > 0 ) {
344 $msg = $title . ( count( $input ) > 1 ?
's' : '' ) . ":\n ";
345 $msg .= implode( $prefix, $input ) . "\n";
352 * Generates the parameter descriptions for this module, to be displayed in the
354 * @return string or false
356 public function makeHelpMsgParameters() {
357 $params = $this->getFinalParams();
360 $paramsDescription = $this->getFinalParamDescription();
362 $paramPrefix = "\n" . str_repeat( ' ', 24 );
363 $descWordwrap = "\n" . str_repeat( ' ', 28 );
364 foreach ( $params as $paramName => $paramSettings ) {
365 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
366 if ( is_array( $desc ) ) {
367 $desc = implode( $paramPrefix, $desc );
370 if ( !is_array( $paramSettings ) ) {
371 $paramSettings = array(
372 self
::PARAM_DFLT
=> $paramSettings,
376 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
377 $paramSettings[self
::PARAM_DEPRECATED
] : false;
379 $desc = "DEPRECATED! $desc";
382 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
383 $paramSettings[self
::PARAM_REQUIRED
] : false;
385 $desc .= $paramPrefix . "This parameter is required";
388 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
389 if ( isset( $type ) ) {
390 if ( isset( $paramSettings[self
::PARAM_ISMULTI
] ) && $paramSettings[self
::PARAM_ISMULTI
] ) {
391 $prompt = 'Values (separate with \'|\'): ';
393 $prompt = 'One value: ';
396 if ( is_array( $type ) ) {
398 $nothingPrompt = false;
399 foreach ( $type as $t ) {
401 $nothingPrompt = 'Can be empty, or ';
406 $desc .= $paramPrefix . $nothingPrompt . $prompt;
407 $choicesstring = implode( ', ', $choices );
408 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
412 // Special handling because namespaces are type-limited, yet they are not given
413 $desc .= $paramPrefix . $prompt;
414 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
415 100, $descWordwrap );
418 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
419 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
420 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
425 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
426 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
427 if ( $hasMin ||
$hasMax ) {
429 $intRangeStr = "The value must be no less than {$paramSettings[self::PARAM_MIN]}";
430 } elseif ( !$hasMin ) {
431 $intRangeStr = "The value must be no more than {$paramSettings[self::PARAM_MAX]}";
433 $intRangeStr = "The value must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
436 $desc .= $paramPrefix . $intRangeStr;
441 if ( isset( $paramSettings[self
::PARAM_ISMULTI
] ) ) {
442 $isArray = is_array( $paramSettings[self
::PARAM_TYPE
] );
445 ||
$isArray && count( $paramSettings[self
::PARAM_TYPE
] ) > self
::LIMIT_SML1
) {
446 $desc .= $paramPrefix . "Maximum number of values " .
447 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
453 $default = is_array( $paramSettings )
454 ?
( isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null )
456 if ( !is_null( $default ) && $default !== false ) {
457 $desc .= $paramPrefix . "Default: $default";
460 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
470 * Callback for preg_replace_callback() call in makeHelpMsg().
471 * Replaces a source file name with a link to ViewVC
473 * @param $matches array
476 public function makeHelpMsg_callback( $matches ) {
477 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
480 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
481 $file = $wgAutoloadLocalClasses[get_class( $this )];
482 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
483 $file = $wgAutoloadClasses[get_class( $this )];
486 // Do some guesswork here
487 $path = strstr( $file, 'includes/api/' );
488 if ( $path === false ) {
489 $path = strstr( $file, 'extensions/' );
491 $path = 'phase3/' . $path;
494 // Get the filename from $matches[2] instead of $file
495 // If they're not the same file, they're assumed to be in the
497 // This is necessary to make stuff like ApiMain::getVersion()
498 // returning the version string for ApiBase work
500 return "{$matches[0]}\n https://svn.wikimedia.org/" .
501 "viewvc/mediawiki/trunk/" . dirname( $path ) .
508 * Returns the description string for this module
509 * @return mixed string or array of strings
511 protected function getDescription() {
516 * Returns usage examples for this module. Return false if no examples are available.
517 * @return bool|string|array
519 protected function getExamples() {
524 * Returns an array of allowed parameters (parameter name) => (default
525 * value) or (parameter name) => (array with PARAM_* constants as keys)
526 * Don't call this function directly: use getFinalParams() to allow
527 * hooks to modify parameters as needed.
530 protected function getAllowedParams() {
535 * Returns an array of parameter descriptions.
536 * Don't call this functon directly: use getFinalParamDescription() to
537 * allow hooks to modify descriptions as needed.
538 * @return array|bool False on no parameter descriptions
540 protected function getParamDescription() {
545 * Get final list of parameters, after hooks have had a chance to
546 * tweak it as needed.
548 * @return array|Bool False on no parameters
550 public function getFinalParams() {
551 $params = $this->getAllowedParams();
552 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
557 * Get final parameter descriptions, after hooks have had a chance to tweak it as
560 * @return array|bool False on no parameter descriptions
562 public function getFinalParamDescription() {
563 $desc = $this->getParamDescription();
564 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
569 * Get final module description, after hooks have had a chance to tweak it as
572 * @return array|bool False on no parameters
574 public function getFinalDescription() {
575 $desc = $this->getDescription();
576 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
581 * This method mangles parameter name based on the prefix supplied to the constructor.
582 * Override this method to change parameter name during runtime
583 * @param $paramName string Parameter name
584 * @return string Prefixed parameter name
586 public function encodeParamName( $paramName ) {
587 return $this->mModulePrefix
. $paramName;
591 * Using getAllowedParams(), this function makes an array of the values
592 * provided by the user, with key being the name of the variable, and
593 * value - validated value from user or default. limits will not be
594 * parsed if $parseLimit is set to false; use this when the max
595 * limit is not definitive yet, e.g. when getting revisions.
596 * @param $parseLimit Boolean: true by default
599 public function extractRequestParams( $parseLimit = true ) {
600 // Cache parameters, for performance and to avoid bug 24564.
601 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
602 $params = $this->getFinalParams();
605 if ( $params ) { // getFinalParams() can return false
606 foreach ( $params as $paramName => $paramSettings ) {
607 $results[$paramName] = $this->getParameterFromSettings(
608 $paramName, $paramSettings, $parseLimit );
611 $this->mParamCache
[$parseLimit] = $results;
613 return $this->mParamCache
[$parseLimit];
617 * Get a value for the given parameter
618 * @param $paramName string Parameter name
619 * @param $parseLimit bool see extractRequestParams()
620 * @return mixed Parameter value
622 protected function getParameter( $paramName, $parseLimit = true ) {
623 $params = $this->getFinalParams();
624 $paramSettings = $params[$paramName];
625 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
629 * Die if none or more than one of a certain set of parameters is set and not false.
630 * @param $params array of parameter names
632 public function requireOnlyOneParameter( $params ) {
633 $required = func_get_args();
634 array_shift( $required );
636 $intersection = array_intersect( array_keys( array_filter( $params,
637 array( $this, "parameterNotEmpty" ) ) ), $required );
639 if ( count( $intersection ) > 1 ) {
640 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
641 } elseif ( count( $intersection ) == 0 ) {
642 $this->dieUsage( 'One of the parameters ' . implode( ', ', $required ) . ' is required', 'missingparam' );
647 * Generates the possible errors requireOnlyOneParameter() can die with
649 * @param $params array
652 public function getRequireOnlyOneParameterErrorMessages( $params ) {
653 $p = $this->getModulePrefix();
654 $params = implode( ", {$p}", $params );
657 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
658 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
663 * Die if more than one of a certain set of parameters is set and not false.
665 * @param $params array
667 public function requireMaxOneParameter( $params ) {
668 $required = func_get_args();
669 array_shift( $required );
671 $intersection = array_intersect( array_keys( array_filter( $params,
672 array( $this, "parameterNotEmpty" ) ) ), $required );
674 if ( count( $intersection ) > 1 ) {
675 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
680 * Generates the possible error requireMaxOneParameter() can die with
682 * @param $params array
685 public function getRequireMaxOneParameterErrorMessages( $params ) {
686 $p = $this->getModulePrefix();
687 $params = implode( ", {$p}", $params );
690 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
695 * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set
697 * @param $x object Parameter to check is not null/false
700 private function parameterNotEmpty( $x ) {
701 return !is_null( $x ) && $x !== false;
705 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
709 public static function getValidNamespaces() {
710 wfDeprecated( __METHOD__
, '1.17' );
711 return MWNamespace
::getValidNamespaces();
715 * Return true if we're to watch the page, false if not, null if no change.
716 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
717 * @param $titleObj Title the page under consideration
718 * @param $userOption String The user option to consider when $watchlist=preferences.
719 * If not set will magically default to either watchdefault or watchcreations
722 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
724 $userWatching = $titleObj->userIsWatching();
726 switch ( $watchlist ) {
734 # If the user is already watching, don't bother checking
735 if ( $userWatching ) {
738 # If no user option was passed, use watchdefault or watchcreation
739 if ( is_null( $userOption ) ) {
740 $userOption = $titleObj->exists()
741 ?
'watchdefault' : 'watchcreations';
743 # Watch the article based on the user preference
744 return (bool)$this->getUser()->getOption( $userOption );
747 return $userWatching;
750 return $userWatching;
755 * Set a watch (or unwatch) based the based on a watchlist parameter.
756 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
757 * @param $titleObj Title the article's title to change
758 * @param $userOption String The user option to consider when $watch=preferences
760 protected function setWatch( $watch, $titleObj, $userOption = null ) {
761 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
762 if ( $value === null ) {
766 $user = $this->getUser();
768 WatchAction
::doWatch( $titleObj, $user );
770 WatchAction
::doUnwatch( $titleObj, $user );
775 * Using the settings determine the value for the given parameter
777 * @param $paramName String: parameter name
778 * @param $paramSettings array|mixed default value or an array of settings
779 * using PARAM_* constants.
780 * @param $parseLimit Boolean: parse limit?
781 * @return mixed Parameter value
783 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
784 // Some classes may decide to change parameter names
785 $encParamName = $this->encodeParamName( $paramName );
787 if ( !is_array( $paramSettings ) ) {
788 $default = $paramSettings;
790 $type = gettype( $paramSettings );
795 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
796 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
797 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
798 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
799 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
800 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
802 // When type is not given, and no choices, the type is the same as $default
803 if ( !isset( $type ) ) {
804 if ( isset( $default ) ) {
805 $type = gettype( $default );
807 $type = 'NULL'; // allow everything
812 if ( $type == 'boolean' ) {
813 if ( isset( $default ) && $default !== false ) {
814 // Having a default value of anything other than 'false' is pointless
815 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'" );
818 $value = $this->getRequest()->getCheck( $encParamName );
820 $value = $this->getRequest()->getVal( $encParamName, $default );
822 if ( isset( $value ) && $type == 'namespace' ) {
823 $type = MWNamespace
::getValidNamespaces();
827 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
828 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
831 // More validation only when choices were not given
832 // choices were validated in parseMultiValue()
833 if ( isset( $value ) ) {
834 if ( !is_array( $type ) ) {
836 case 'NULL': // nothing to do
839 if ( $required && $value === '' ) {
840 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
844 case 'integer': // Force everything using intval() and optionally validate limits
845 $min = isset ( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
846 $max = isset ( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
847 $enforceLimits = isset ( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
848 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
850 if ( is_array( $value ) ) {
851 $value = array_map( 'intval', $value );
852 if ( !is_null( $min ) ||
!is_null( $max ) ) {
853 foreach ( $value as &$v ) {
854 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
858 $value = intval( $value );
859 if ( !is_null( $min ) ||
!is_null( $max ) ) {
860 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
865 if ( !$parseLimit ) {
866 // Don't do any validation whatsoever
869 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
870 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
873 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
875 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
876 if ( $value == 'max' ) {
877 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
878 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
880 $value = intval( $value );
881 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
886 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
890 if ( is_array( $value ) ) {
891 foreach ( $value as $key => $val ) {
892 $value[$key] = $this->validateTimestamp( $val, $encParamName );
895 $value = $this->validateTimestamp( $value, $encParamName );
899 if ( !is_array( $value ) ) {
900 $value = array( $value );
903 foreach ( $value as $key => $val ) {
904 $title = Title
::makeTitleSafe( NS_USER
, $val );
905 if ( is_null( $title ) ) {
906 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
908 $value[$key] = $title->getText();
916 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
920 // Throw out duplicates if requested
921 if ( is_array( $value ) && !$dupes ) {
922 $value = array_unique( $value );
925 // Set a warning if a deprecated parameter has been passed
926 if ( $deprecated && $value !== false ) {
927 $this->setWarning( "The $encParamName parameter has been deprecated." );
929 } elseif ( $required ) {
930 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
937 * Return an array of values that were given in a 'a|b|c' notation,
938 * after it optionally validates them against the list allowed values.
940 * @param $valueName string The name of the parameter (for error
942 * @param $value mixed The value being parsed
943 * @param $allowMultiple bool Can $value contain more than one value
945 * @param $allowedValues mixed An array of values to check against. If
946 * null, all values are accepted.
947 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
949 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
950 if ( trim( $value ) === '' && $allowMultiple ) {
954 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
955 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
956 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
957 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
959 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
960 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
963 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
964 // Bug 33482 - Allow entries with | in them for non-multiple values
965 if ( in_array( $value, $allowedValues ) ) {
969 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
970 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
973 if ( is_array( $allowedValues ) ) {
974 // Check for unknown values
975 $unknown = array_diff( $valuesList, $allowedValues );
976 if ( count( $unknown ) ) {
977 if ( $allowMultiple ) {
978 $s = count( $unknown ) > 1 ?
's' : '';
979 $vals = implode( ", ", $unknown );
980 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
982 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
985 // Now throw them out
986 $valuesList = array_intersect( $valuesList, $allowedValues );
989 return $allowMultiple ?
$valuesList : $valuesList[0];
993 * Validate the value against the minimum and user/bot maximum limits.
994 * Prints usage info on failure.
995 * @param $paramName string Parameter name
996 * @param $value int Parameter value
997 * @param $min int|null Minimum value
998 * @param $max int|null Maximum value for users
999 * @param $botMax int Maximum value for sysops/bots
1000 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1002 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1003 if ( !is_null( $min ) && $value < $min ) {
1005 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1006 $this->warnOrDie( $msg, $enforceLimits );
1010 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1011 if ( $this->getMain()->isInternalMode() ) {
1015 // Optimization: do not check user's bot status unless really needed -- skips db query
1016 // assumes $botMax >= $max
1017 if ( !is_null( $max ) && $value > $max ) {
1018 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1019 if ( $value > $botMax ) {
1020 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1021 $this->warnOrDie( $msg, $enforceLimits );
1025 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1026 $this->warnOrDie( $msg, $enforceLimits );
1033 * @param $value string
1034 * @param $paramName string
1037 function validateTimestamp( $value, $paramName ) {
1038 $value = wfTimestamp( TS_UNIX
, $value );
1039 if ( $value === 0 ) {
1040 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
1042 return wfTimestamp( TS_MW
, $value );
1046 * Adds a warning to the output, else dies
1048 * @param $msg String Message to show as a warning, or error message if dying
1049 * @param $enforceLimits Boolean Whether this is an enforce (die)
1051 private function warnOrDie( $msg, $enforceLimits = false ) {
1052 if ( $enforceLimits ) {
1053 $this->dieUsage( $msg, 'integeroutofrange' );
1055 $this->setWarning( $msg );
1060 * Truncate an array to a certain length.
1061 * @param $arr array Array to truncate
1062 * @param $limit int Maximum length
1063 * @return bool True if the array was truncated, false otherwise
1065 public static function truncateArray( &$arr, $limit ) {
1067 while ( count( $arr ) > $limit ) {
1075 * Throw a UsageException, which will (if uncaught) call the main module's
1076 * error handler and die with an error message.
1078 * @param $description string One-line human-readable description of the
1079 * error condition, e.g., "The API requires a valid action parameter"
1080 * @param $errorCode string Brief, arbitrary, stable string to allow easy
1081 * automated identification of the error, e.g., 'unknown_action'
1082 * @param $httpRespCode int HTTP response code
1083 * @param $extradata array Data to add to the <error> element; array in ApiResult format
1085 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1086 Profiler
::instance()->close();
1087 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1091 * Array that maps message keys to error messages. $1 and friends are replaced.
1093 public static $messageMap = array(
1094 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1095 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1096 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1098 // Messages from Title::getUserPermissionsErrors()
1099 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1100 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1101 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1102 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1103 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1104 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1105 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1106 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1107 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1108 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1109 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1110 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1111 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1112 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1113 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1114 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
1115 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1116 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1118 // Miscellaneous interface messages
1119 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1120 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1121 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1122 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1123 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1124 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1125 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1126 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1127 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1128 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1129 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1130 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1131 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1132 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1133 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1134 // 'badarticleerror' => shouldn't happen
1135 // 'badtitletext' => shouldn't happen
1136 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1137 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1138 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1139 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1140 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1141 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1142 '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." ),
1143 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1144 '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" ),
1145 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1146 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1147 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1148 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
1149 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1150 '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" ),
1151 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1152 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1153 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1154 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1155 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1156 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1157 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1158 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1159 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1161 // API-specific messages
1162 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1163 '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" ),
1164 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1165 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1166 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1167 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1168 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1169 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1170 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1171 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1172 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1173 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1174 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1175 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1176 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1177 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
1178 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1179 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1180 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1181 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1182 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1183 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1184 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1185 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1186 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1187 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1188 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1189 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1190 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1191 'nouploadmodule' => array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
1192 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1193 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1194 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1195 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1196 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1197 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1198 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1199 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1200 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1201 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1202 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1203 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1204 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1205 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1206 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1208 // ApiEditPage messages
1209 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1210 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1211 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1212 'filtered' => array( 'code' => 'filtered', 'info' => "The filter callback function refused your edit" ),
1213 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1214 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1215 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1216 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1217 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1218 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1219 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1220 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1221 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1222 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1223 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1225 // Messages from WikiPage::doEit()
1226 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1227 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1228 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1229 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1232 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ),
1233 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1234 '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' ),
1235 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1236 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1238 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1239 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1240 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1241 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1243 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1247 * Helper function for readonly errors
1249 public function dieReadOnly() {
1250 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1251 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1252 array( 'readonlyreason' => wfReadOnlyReason() ) );
1256 * Output the error message related to a certain array
1257 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1259 public function dieUsageMsg( $error ) {
1260 # most of the time we send a 1 element, so we might as well send it as
1261 # a string and make this an array here.
1262 if( is_string( $error ) ) {
1263 $error = array( $error );
1265 $parsed = $this->parseMsg( $error );
1266 $this->dieUsage( $parsed['info'], $parsed['code'] );
1270 * Return the error message related to a certain array
1271 * @param $error array Element of a getUserPermissionsErrors()-style array
1272 * @return array('code' => code, 'info' => info)
1274 public function parseMsg( $error ) {
1275 $key = array_shift( $error );
1277 // Check whether the error array was nested
1278 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1279 if( is_array( $key ) ){
1281 $key = array_shift( $error );
1284 if ( isset( self
::$messageMap[$key] ) ) {
1285 return array( 'code' =>
1286 wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1288 wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1292 // If the key isn't present, throw an "unknown error"
1293 return $this->parseMsg( array( 'unknownerror', $key ) );
1297 * Internal code errors should be reported with this method
1298 * @param $method string Method or function name
1299 * @param $message string Error message
1301 protected static function dieDebug( $method, $message ) {
1302 wfDebugDieBacktrace( "Internal error in $method: $message" );
1306 * Indicates if this module needs maxlag to be checked
1309 public function shouldCheckMaxlag() {
1314 * Indicates whether this module requires read rights
1317 public function isReadMode() {
1321 * Indicates whether this module requires write mode
1324 public function isWriteMode() {
1329 * Indicates whether this module must be called with a POST request
1332 public function mustBePosted() {
1337 * Returns whether this module requires a Token to execute
1340 public function needsToken() {
1345 * Returns the token salt if there is one, '' if the module doesn't require a salt, else false if the module doesn't need a token
1346 * @return bool|string
1348 public function getTokenSalt() {
1353 * Gets the user for whom to get the watchlist
1355 * @param $params array
1358 public function getWatchlistUser( $params ) {
1359 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1360 $user = User
::newFromName( $params['owner'], false );
1361 if ( !($user && $user->getId()) ) {
1362 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1364 $token = $user->getOption( 'watchlisttoken' );
1365 if ( $token == '' ||
$token != $params['token'] ) {
1366 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1369 if ( !$this->getUser()->isLoggedIn() ) {
1370 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1372 $user = $this->getUser();
1378 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1380 public function getHelpUrls() {
1385 * Returns a list of all possible errors returned by the module
1386 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1388 public function getPossibleErrors() {
1391 $params = $this->getFinalParams();
1393 foreach ( $params as $paramName => $paramSettings ) {
1394 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) ) {
1395 $ret[] = array( 'missingparam', $paramName );
1400 if ( $this->mustBePosted() ) {
1401 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1404 if ( $this->isReadMode() ) {
1405 $ret[] = array( 'readrequired' );
1408 if ( $this->isWriteMode() ) {
1409 $ret[] = array( 'writerequired' );
1410 $ret[] = array( 'writedisabled' );
1413 if ( $this->needsToken() ) {
1414 $ret[] = array( 'missingparam', 'token' );
1415 $ret[] = array( 'sessionfailure' );
1422 * Parses a list of errors into a standardised format
1423 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1424 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1426 public function parseErrors( $errors ) {
1429 foreach ( $errors as $row ) {
1430 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1433 $ret[] = $this->parseMsg( $row );
1440 * Profiling: total module execution time
1442 private $mTimeIn = 0, $mModuleTime = 0;
1445 * Start module profiling
1447 public function profileIn() {
1448 if ( $this->mTimeIn
!== 0 ) {
1449 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1451 $this->mTimeIn
= microtime( true );
1452 wfProfileIn( $this->getModuleProfileName() );
1456 * End module profiling
1458 public function profileOut() {
1459 if ( $this->mTimeIn
=== 0 ) {
1460 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1462 if ( $this->mDBTimeIn
!== 0 ) {
1463 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1466 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1468 wfProfileOut( $this->getModuleProfileName() );
1472 * When modules crash, sometimes it is needed to do a profileOut() regardless
1473 * of the profiling state the module was in. This method does such cleanup.
1475 public function safeProfileOut() {
1476 if ( $this->mTimeIn
!== 0 ) {
1477 if ( $this->mDBTimeIn
!== 0 ) {
1478 $this->profileDBOut();
1480 $this->profileOut();
1485 * Total time the module was executed
1488 public function getProfileTime() {
1489 if ( $this->mTimeIn
!== 0 ) {
1490 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1492 return $this->mModuleTime
;
1496 * Profiling: database execution time
1498 private $mDBTimeIn = 0, $mDBTime = 0;
1501 * Start module profiling
1503 public function profileDBIn() {
1504 if ( $this->mTimeIn
=== 0 ) {
1505 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1507 if ( $this->mDBTimeIn
!== 0 ) {
1508 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1510 $this->mDBTimeIn
= microtime( true );
1511 wfProfileIn( $this->getModuleProfileName( true ) );
1515 * End database profiling
1517 public function profileDBOut() {
1518 if ( $this->mTimeIn
=== 0 ) {
1519 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1521 if ( $this->mDBTimeIn
=== 0 ) {
1522 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1525 $time = microtime( true ) - $this->mDBTimeIn
;
1526 $this->mDBTimeIn
= 0;
1528 $this->mDBTime +
= $time;
1529 $this->getMain()->mDBTime +
= $time;
1530 wfProfileOut( $this->getModuleProfileName( true ) );
1534 * Total time the module used the database
1537 public function getProfileDBTime() {
1538 if ( $this->mDBTimeIn
!== 0 ) {
1539 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1541 return $this->mDBTime
;
1545 * @return DatabaseBase
1547 protected function getDB() {
1548 return wfGetDB( DB_SLAVE
, 'api' );
1552 * Debugging function that prints a value and an optional backtrace
1553 * @param $value mixed Value to print
1554 * @param $name string Description of the printed value
1555 * @param $backtrace bool If true, print a backtrace
1557 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1558 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1559 var_export( $value );
1561 print "\n" . wfBacktrace();
1567 * Returns a string that identifies the version of this class.
1570 public static function getBaseVersion() {
1571 return __CLASS__
. ': $Id$';