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
{
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)
54 const PARAM_REQUIRED
= 8; // Boolean, is the parameter required?
55 const PARAM_RANGE_ENFORCE
= 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
57 const LIMIT_BIG1
= 500; // Fast query, std user limit
58 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
59 const LIMIT_SML1
= 50; // Slow query, std user limit
60 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
62 private $mMainModule, $mModuleName, $mModulePrefix;
63 private $mParamCache = array();
67 * @param $mainModule ApiMain object
68 * @param $moduleName string Name of this module
69 * @param $modulePrefix string Prefix to use for parameter names
71 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
72 $this->mMainModule
= $mainModule;
73 $this->mModuleName
= $moduleName;
74 $this->mModulePrefix
= $modulePrefix;
77 /*****************************************************************************
79 *****************************************************************************/
82 * Evaluates the parameters, performs the requested query, and sets up
83 * the result. Concrete implementations of ApiBase must override this
84 * method to provide whatever functionality their module offers.
85 * Implementations must not produce any output on their own and are not
86 * expected to handle any errors.
88 * The execute() method will be invoked directly by ApiMain immediately
89 * before the result of the module is output. Aside from the
90 * constructor, implementations should assume that no other methods
91 * will be called externally on the module before the result is
94 * The result data should be stored in the ApiResult object available
95 * through getResult().
97 public abstract function execute();
100 * Returns a string that identifies the version of the extending class.
101 * Typically includes the class name, the svn revision, timestamp, and
102 * last author. Usually done with SVN's Id keyword
105 public abstract function getVersion();
108 * Get the name of the module being executed by this instance
111 public function getModuleName() {
112 return $this->mModuleName
;
116 * Get parameter prefix (usually two letters or an empty string).
119 public function getModulePrefix() {
120 return $this->mModulePrefix
;
124 * Get the name of the module as shown in the profiler log
126 * @param $db DatabaseBase
130 public function getModuleProfileName( $db = false ) {
132 return 'API:' . $this->mModuleName
. '-DB';
134 return 'API:' . $this->mModuleName
;
139 * Get the main module
140 * @return ApiMain object
142 public function getMain() {
143 return $this->mMainModule
;
147 * Returns true if this module is the main module ($this === $this->mMainModule),
151 public function isMain() {
152 return $this === $this->mMainModule
;
156 * Get the result object
159 public function getResult() {
160 // Main module has getResult() method overriden
161 // Safety - avoid infinite loop:
162 if ( $this->isMain() ) {
163 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
165 return $this->getMain()->getResult();
169 * Get the result data array (read-only)
172 public function getResultData() {
173 return $this->getResult()->getData();
177 * Set warning section for this module. Users should monitor this
178 * section to notice any changes in API. Multiple calls to this
179 * function will result in the warning messages being separated by
181 * @param $warning string Warning message
183 public function setWarning( $warning ) {
184 $data = $this->getResult()->getData();
185 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
186 // Don't add duplicate warnings
187 $warn_regex = preg_quote( $warning, '/' );
188 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
191 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
192 // If there is a warning already, append it to the existing one
193 $warning = "$oldwarning\n$warning";
194 $this->getResult()->unsetValue( 'warnings', $this->getModuleName() );
197 ApiResult
::setContent( $msg, $warning );
198 $this->getResult()->disableSizeCheck();
199 $this->getResult()->addValue( 'warnings', $this->getModuleName(), $msg );
200 $this->getResult()->enableSizeCheck();
204 * If the module may only be used with a certain format module,
205 * it should override this method to return an instance of that formatter.
206 * A value of null means the default format will be used.
207 * @return mixed instance of a derived class of ApiFormatBase, or null
209 public function getCustomPrinter() {
214 * Generates help message for this module, or false if there is no description
215 * @return mixed string or false
217 public function makeHelpMsg() {
218 static $lnPrfx = "\n ";
220 $msg = $this->getDescription();
222 if ( $msg !== false ) {
224 if ( !is_array( $msg ) ) {
229 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
231 if ( $this->isReadMode() ) {
232 $msg .= "\nThis module requires read rights";
234 if ( $this->isWriteMode() ) {
235 $msg .= "\nThis module requires write rights";
237 if ( $this->mustBePosted() ) {
238 $msg .= "\nThis module only accepts POST requests";
240 if ( $this->isReadMode() ||
$this->isWriteMode() ||
241 $this->mustBePosted() )
247 $paramsMsg = $this->makeHelpMsgParameters();
248 if ( $paramsMsg !== false ) {
249 $msg .= "Parameters:\n$paramsMsg";
253 $examples = $this->getExamples();
254 if ( $examples !== false ) {
255 if ( !is_array( $examples ) ) {
261 if ( count( $examples ) > 0 ) {
262 $msg .= 'Example' . ( count( $examples ) > 1 ?
's' : '' ) . ":\n ";
263 $msg .= implode( $lnPrfx, $examples ) . "\n";
267 if ( $this->getMain()->getShowVersions() ) {
268 $versions = $this->getVersion();
269 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
270 $callback = array( $this, 'makeHelpMsg_callback' );
272 if ( is_array( $versions ) ) {
273 foreach ( $versions as &$v ) {
274 $v = preg_replace_callback( $pattern, $callback, $v );
276 $versions = implode( "\n ", $versions );
278 $versions = preg_replace_callback( $pattern, $callback, $versions );
281 $msg .= "Version:\n $versions\n";
289 * Generates the parameter descriptions for this module, to be displayed in the
291 * @return string or false
293 public function makeHelpMsgParameters() {
294 $params = $this->getFinalParams();
297 $paramsDescription = $this->getFinalParamDescription();
299 $paramPrefix = "\n" . str_repeat( ' ', 24 );
300 $descWordwrap = "\n" . str_repeat( ' ', 28 );
301 foreach ( $params as $paramName => $paramSettings ) {
302 $desc = isset( $paramsDescription[$paramName] ) ?
$paramsDescription[$paramName] : '';
303 if ( is_array( $desc ) ) {
304 $desc = implode( $paramPrefix, $desc );
307 if ( !is_array( $paramSettings ) ) {
308 $paramSettings = array(
309 self
::PARAM_DFLT
=> $paramSettings,
313 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
314 $paramSettings[self
::PARAM_DEPRECATED
] : false;
316 $desc = "DEPRECATED! $desc";
319 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
320 $paramSettings[self
::PARAM_REQUIRED
] : false;
322 $desc .= $paramPrefix . "This parameter is required";
325 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
326 if ( isset( $type ) ) {
327 if ( isset( $paramSettings[self
::PARAM_ISMULTI
] ) ) {
328 $prompt = 'Values (separate with \'|\'): ';
330 $prompt = 'One value: ';
333 if ( is_array( $type ) ) {
335 $nothingPrompt = false;
336 foreach ( $type as $t ) {
338 $nothingPrompt = 'Can be empty, or ';
343 $desc .= $paramPrefix . $nothingPrompt . $prompt;
344 $choicesstring = implode( ', ', $choices );
345 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
349 // Special handling because namespaces are type-limited, yet they are not given
350 $desc .= $paramPrefix . $prompt;
351 $desc .= wordwrap( implode( ', ', MWNamespace
::getValidNamespaces() ),
352 100, $descWordwrap );
355 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
356 if ( isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
357 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
362 $hasMin = isset( $paramSettings[self
::PARAM_MIN
] );
363 $hasMax = isset( $paramSettings[self
::PARAM_MAX
] );
364 if ( $hasMin ||
$hasMax ) {
366 $intRangeStr = "The value must be no less than {$paramSettings[self::PARAM_MIN]}";
367 } elseif ( !$hasMin ) {
368 $intRangeStr = "The value must be no more than {$paramSettings[self::PARAM_MAX]}";
370 $intRangeStr = "The value must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
373 $desc .= $paramPrefix . $intRangeStr;
378 if ( isset( $paramSettings[self
::PARAM_ISMULTI
] ) ) {
379 $isArray = is_array( $paramSettings[self
::PARAM_TYPE
] );
382 ||
$isArray && count( $paramSettings[self
::PARAM_TYPE
] ) > self
::LIMIT_SML1
) {
383 $desc .= $paramPrefix . "Maximum number of values " .
384 self
::LIMIT_SML1
. " (" . self
::LIMIT_SML2
. " for bots)";
390 $default = is_array( $paramSettings )
391 ?
( isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null )
393 if ( !is_null( $default ) && $default !== false ) {
394 $desc .= $paramPrefix . "Default: $default";
397 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
407 * Callback for preg_replace_callback() call in makeHelpMsg().
408 * Replaces a source file name with a link to ViewVC
412 public function makeHelpMsg_callback( $matches ) {
413 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
416 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
417 $file = $wgAutoloadLocalClasses[get_class( $this )];
418 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
419 $file = $wgAutoloadClasses[get_class( $this )];
422 // Do some guesswork here
423 $path = strstr( $file, 'includes/api/' );
424 if ( $path === false ) {
425 $path = strstr( $file, 'extensions/' );
427 $path = 'phase3/' . $path;
430 // Get the filename from $matches[2] instead of $file
431 // If they're not the same file, they're assumed to be in the
433 // This is necessary to make stuff like ApiMain::getVersion()
434 // returning the version string for ApiBase work
436 return "{$matches[0]}\n http://svn.wikimedia.org/" .
437 "viewvc/mediawiki/trunk/" . dirname( $path ) .
444 * Returns the description string for this module
445 * @return mixed string or array of strings
447 protected function getDescription() {
452 * Returns usage examples for this module. Return null if no examples are available.
453 * @return mixed string or array of strings
455 protected function getExamples() {
460 * Returns an array of allowed parameters (parameter name) => (default
461 * value) or (parameter name) => (array with PARAM_* constants as keys)
462 * Don't call this function directly: use getFinalParams() to allow
463 * hooks to modify parameters as needed.
464 * @return array or false
466 protected function getAllowedParams() {
471 * Returns an array of parameter descriptions.
472 * Don't call this functon directly: use getFinalParamDescription() to
473 * allow hooks to modify descriptions as needed.
474 * @return array or false
476 protected function getParamDescription() {
481 * Get final list of parameters, after hooks have had a chance to
482 * tweak it as needed.
483 * @return array or false
485 public function getFinalParams() {
486 $params = $this->getAllowedParams();
487 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
492 * Get final description, after hooks have had a chance to tweak it as
496 public function getFinalParamDescription() {
497 $desc = $this->getParamDescription();
498 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
503 * This method mangles parameter name based on the prefix supplied to the constructor.
504 * Override this method to change parameter name during runtime
505 * @param $paramName string Parameter name
506 * @return string Prefixed parameter name
508 public function encodeParamName( $paramName ) {
509 return $this->mModulePrefix
. $paramName;
513 * Using getAllowedParams(), this function makes an array of the values
514 * provided by the user, with key being the name of the variable, and
515 * value - validated value from user or default. limits will not be
516 * parsed if $parseLimit is set to false; use this when the max
517 * limit is not definitive yet, e.g. when getting revisions.
518 * @param $parseLimit Boolean: true by default
521 public function extractRequestParams( $parseLimit = true ) {
522 // Cache parameters, for performance and to avoid bug 24564.
523 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
524 $params = $this->getFinalParams();
527 if ( $params ) { // getFinalParams() can return false
528 foreach ( $params as $paramName => $paramSettings ) {
529 $results[$paramName] = $this->getParameterFromSettings(
530 $paramName, $paramSettings, $parseLimit );
533 $this->mParamCache
[$parseLimit] = $results;
535 return $this->mParamCache
[$parseLimit];
539 * Get a value for the given parameter
540 * @param $paramName string Parameter name
541 * @param $parseLimit bool see extractRequestParams()
542 * @return mixed Parameter value
544 protected function getParameter( $paramName, $parseLimit = true ) {
545 $params = $this->getFinalParams();
546 $paramSettings = $params[$paramName];
547 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
551 * Die if none or more than one of a certain set of parameters is set and not false.
552 * @param $params array of parameter names
554 public function requireOnlyOneParameter( $params ) {
555 $required = func_get_args();
556 array_shift( $required );
558 $intersection = array_intersect( array_keys( array_filter( $params,
559 array( $this, "parameterNotEmpty" ) ) ), $required );
561 if ( count( $intersection ) > 1 ) {
562 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
563 } elseif ( count( $intersection ) == 0 ) {
564 $this->dieUsage( 'One of the parameters ' . implode( ', ', $required ) . ' is required', 'missingparam' );
569 * Generates the possible errors requireOnlyOneParameter() can die with
571 * @param $params array
574 public function getRequireOnlyOneParameterErrorMessages( $params ) {
575 $p = $this->getModulePrefix();
576 $params = implode( ", {$p}", $params );
579 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
580 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
585 * Die if more than one of a certain set of parameters is set and not false.
587 * @param $params array
589 public function requireMaxOneParameter( $params ) {
590 $required = func_get_args();
591 array_shift( $required );
593 $intersection = array_intersect( array_keys( array_filter( $params,
594 array( $this, "parameterNotEmpty" ) ) ), $required );
596 if ( count( $intersection ) > 1 ) {
597 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
602 * Generates the possible error requireMaxOneParameter() can die with
604 * @param $params array
607 public function getRequireMaxOneParameterErrorMessages( $params ) {
608 $p = $this->getModulePrefix();
609 $params = implode( ", {$p}", $params );
612 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
617 * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set
619 * @param $x object Parameter to check is not null/false
622 private function parameterNotEmpty( $x ) {
623 return !is_null( $x ) && $x !== false;
627 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
629 public static function getValidNamespaces() {
630 return MWNamespace
::getValidNamespaces();
634 * Return true if we're to watch the page, false if not, null if no change.
635 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
636 * @param $titleObj Title the page under consideration
637 * @param $userOption String The user option to consider when $watchlist=preferences.
638 * If not set will magically default to either watchdefault or watchcreations
641 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
643 $userWatching = $titleObj->userIsWatching();
646 switch ( $watchlist ) {
654 # If the user is already watching, don't bother checking
655 if ( $userWatching ) {
658 # If no user option was passed, use watchdefault or watchcreation
659 if ( is_null( $userOption ) ) {
660 $userOption = $titleObj->exists()
661 ?
'watchdefault' : 'watchcreations';
663 # Watch the article based on the user preference
664 return (bool)$wgUser->getOption( $userOption );
667 return $userWatching;
670 return $userWatching;
675 * Set a watch (or unwatch) based the based on a watchlist parameter.
676 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
677 * @param $titleObj Title the article's title to change
678 * @param $userOption String The user option to consider when $watch=preferences
680 protected function setWatch( $watch, $titleObj, $userOption = null ) {
681 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
682 if ( $value === null ) {
688 WatchAction
::doWatch( $titleObj, $wgUser );
690 WatchAction
::doUnwatch( $titleObj, $wgUser );
695 * Using the settings determine the value for the given parameter
697 * @param $paramName String: parameter name
698 * @param $paramSettings Mixed: default value or an array of settings
699 * using PARAM_* constants.
700 * @param $parseLimit Boolean: parse limit?
701 * @return mixed Parameter value
703 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
704 // Some classes may decide to change parameter names
705 $encParamName = $this->encodeParamName( $paramName );
707 if ( !is_array( $paramSettings ) ) {
708 $default = $paramSettings;
710 $type = gettype( $paramSettings );
715 $default = isset( $paramSettings[self
::PARAM_DFLT
] ) ?
$paramSettings[self
::PARAM_DFLT
] : null;
716 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] ) ?
$paramSettings[self
::PARAM_ISMULTI
] : false;
717 $type = isset( $paramSettings[self
::PARAM_TYPE
] ) ?
$paramSettings[self
::PARAM_TYPE
] : null;
718 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] ) ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
] : false;
719 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] ) ?
$paramSettings[self
::PARAM_DEPRECATED
] : false;
720 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] ) ?
$paramSettings[self
::PARAM_REQUIRED
] : false;
722 // When type is not given, and no choices, the type is the same as $default
723 if ( !isset( $type ) ) {
724 if ( isset( $default ) ) {
725 $type = gettype( $default );
727 $type = 'NULL'; // allow everything
732 if ( $type == 'boolean' ) {
733 if ( isset( $default ) && $default !== false ) {
734 // Having a default value of anything other than 'false' is pointless
735 ApiBase
::dieDebug( __METHOD__
, "Boolean param $encParamName's default is set to '$default'" );
738 $value = $this->getMain()->getRequest()->getCheck( $encParamName );
740 $value = $this->getMain()->getRequest()->getVal( $encParamName, $default );
742 if ( isset( $value ) && $type == 'namespace' ) {
743 $type = MWNamespace
::getValidNamespaces();
747 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
748 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ?
$type : null );
751 // More validation only when choices were not given
752 // choices were validated in parseMultiValue()
753 if ( isset( $value ) ) {
754 if ( !is_array( $type ) ) {
756 case 'NULL': // nothing to do
759 if ( $required && $value === '' ) {
760 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
764 case 'integer': // Force everything using intval() and optionally validate limits
765 $min = isset ( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
766 $max = isset ( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
767 $enforceLimits = isset ( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
768 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
770 if ( is_array( $value ) ) {
771 $value = array_map( 'intval', $value );
772 if ( !is_null( $min ) ||
!is_null( $max ) ) {
773 foreach ( $value as &$v ) {
774 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
778 $value = intval( $value );
779 if ( !is_null( $min ) ||
!is_null( $max ) ) {
780 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
785 if ( !$parseLimit ) {
786 // Don't do any validation whatsoever
789 if ( !isset( $paramSettings[self
::PARAM_MAX
] ) ||
!isset( $paramSettings[self
::PARAM_MAX2
] ) ) {
790 ApiBase
::dieDebug( __METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName" );
793 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
795 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
796 if ( $value == 'max' ) {
797 $value = $this->getMain()->canApiHighLimits() ?
$paramSettings[self
::PARAM_MAX2
] : $paramSettings[self
::PARAM_MAX
];
798 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
800 $value = intval( $value );
801 $this->validateLimit( $paramName, $value, $min, $paramSettings[self
::PARAM_MAX
], $paramSettings[self
::PARAM_MAX2
] );
806 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
810 if ( is_array( $value ) ) {
811 foreach ( $value as $key => $val ) {
812 $value[$key] = $this->validateTimestamp( $val, $encParamName );
815 $value = $this->validateTimestamp( $value, $encParamName );
819 if ( !is_array( $value ) ) {
820 $value = array( $value );
823 foreach ( $value as $key => $val ) {
824 $title = Title
::makeTitleSafe( NS_USER
, $val );
825 if ( is_null( $title ) ) {
826 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
828 $value[$key] = $title->getText();
836 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
840 // Throw out duplicates if requested
841 if ( is_array( $value ) && !$dupes ) {
842 $value = array_unique( $value );
845 // Set a warning if a deprecated parameter has been passed
846 if ( $deprecated && $value !== false ) {
847 $this->setWarning( "The $encParamName parameter has been deprecated." );
849 } elseif ( $required ) {
850 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
857 * Return an array of values that were given in a 'a|b|c' notation,
858 * after it optionally validates them against the list allowed values.
860 * @param $valueName string The name of the parameter (for error
862 * @param $value mixed The value being parsed
863 * @param $allowMultiple bool Can $value contain more than one value
865 * @param $allowedValues mixed An array of values to check against. If
866 * null, all values are accepted.
867 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
869 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
870 if ( trim( $value ) === '' && $allowMultiple ) {
874 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
875 $valuesList = explode( '|', $value, self
::LIMIT_SML2 +
1 );
876 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits() ?
877 self
::LIMIT_SML2
: self
::LIMIT_SML1
;
879 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
880 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
883 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
884 $possibleValues = is_array( $allowedValues ) ?
"of '" . implode( "', '", $allowedValues ) . "'" : '';
885 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
888 if ( is_array( $allowedValues ) ) {
889 // Check for unknown values
890 $unknown = array_diff( $valuesList, $allowedValues );
891 if ( count( $unknown ) ) {
892 if ( $allowMultiple ) {
893 $s = count( $unknown ) > 1 ?
's' : '';
894 $vals = implode( ", ", $unknown );
895 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
897 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
900 // Now throw them out
901 $valuesList = array_intersect( $valuesList, $allowedValues );
904 return $allowMultiple ?
$valuesList : $valuesList[0];
908 * Validate the value against the minimum and user/bot maximum limits.
909 * Prints usage info on failure.
910 * @param $paramName string Parameter name
911 * @param $value int Parameter value
912 * @param $min int|null Minimum value
913 * @param $max int|null Maximum value for users
914 * @param $botMax int Maximum value for sysops/bots
915 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
917 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
918 if ( !is_null( $min ) && $value < $min ) {
920 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
921 $this->warnOrDie( $msg, $enforceLimits );
925 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
926 if ( $this->getMain()->isInternalMode() ) {
930 // Optimization: do not check user's bot status unless really needed -- skips db query
931 // assumes $botMax >= $max
932 if ( !is_null( $max ) && $value > $max ) {
933 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
934 if ( $value > $botMax ) {
935 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
936 $this->warnOrDie( $msg, $enforceLimits );
940 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
941 $this->warnOrDie( $msg, $enforceLimits );
948 * @param $value string
949 * @param $paramName string
952 function validateTimestamp( $value, $paramName ) {
953 $value = wfTimestamp( TS_UNIX
, $value );
954 if ( $value === 0 ) {
955 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
957 return wfTimestamp( TS_MW
, $value );
961 * Adds a warning to the output, else dies
963 * @param $msg String Message to show as a warning, or error message if dying
964 * @param $enforceLimits Boolean Whether this is an enforce (die)
966 private function warnOrDie( $msg, $enforceLimits = false ) {
967 if ( $enforceLimits ) {
968 $this->dieUsage( $msg, 'integeroutofrange' );
970 $this->setWarning( $msg );
975 * Truncate an array to a certain length.
976 * @param $arr array Array to truncate
977 * @param $limit int Maximum length
978 * @return bool True if the array was truncated, false otherwise
980 public static function truncateArray( &$arr, $limit ) {
982 while ( count( $arr ) > $limit ) {
990 * Throw a UsageException, which will (if uncaught) call the main module's
991 * error handler and die with an error message.
993 * @param $description string One-line human-readable description of the
994 * error condition, e.g., "The API requires a valid action parameter"
995 * @param $errorCode string Brief, arbitrary, stable string to allow easy
996 * automated identification of the error, e.g., 'unknown_action'
997 * @param $httpRespCode int HTTP response code
998 * @param $extradata array Data to add to the <error> element; array in ApiResult format
1000 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1001 Profiler
::instance()->close();
1002 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1006 * Array that maps message keys to error messages. $1 and friends are replaced.
1008 public static $messageMap = array(
1009 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1010 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: ``\$1''" ),
1011 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1013 // Messages from Title::getUserPermissionsErrors()
1014 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1015 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1016 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace" ),
1017 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1018 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1019 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1020 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page" ),
1021 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1022 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1023 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1024 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1025 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1026 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1027 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1028 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1029 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
1030 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1031 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1033 // Miscellaneous interface messages
1034 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1035 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1036 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1037 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1038 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1039 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else" ),
1040 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1041 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1042 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1043 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1044 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1045 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1046 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1047 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1048 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1049 // 'badarticleerror' => shouldn't happen
1050 // 'badtitletext' => shouldn't happen
1051 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1052 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1053 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1054 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1055 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1056 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1057 '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." ),
1058 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1059 '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" ),
1060 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1061 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1062 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1063 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
1064 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1065 '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" ),
1066 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1067 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1068 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1069 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1070 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1071 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database ``\$1'' does not exist or is not local" ),
1072 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
1073 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
1074 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1076 // API-specific messages
1077 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1078 '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" ),
1079 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1080 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1081 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title ``\$1''" ),
1082 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1083 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1084 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User ``\$1'' doesn't exist" ),
1085 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
1086 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''" ),
1087 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past" ),
1088 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1089 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1090 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1091 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1092 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
1093 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1094 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1095 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1096 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1097 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1098 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1099 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1100 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''" ),
1101 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''" ),
1102 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''" ),
1103 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1104 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1105 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1106 'nouploadmodule' => array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
1107 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1108 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1109 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1110 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1111 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1112 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1113 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1114 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: ``\$1''" ),
1115 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1116 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1117 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1118 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1119 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1121 // ApiEditPage messages
1122 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1123 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1124 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''" ),
1125 'filtered' => array( 'code' => 'filtered', 'info' => "The filter callback function refused your edit" ),
1126 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1127 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1128 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1129 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1130 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1131 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1132 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1133 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1134 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1135 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of ``\$2''" ),
1136 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1139 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ),
1140 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1141 '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' ),
1142 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1144 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1145 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1146 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1150 * Helper function for readonly errors
1152 public function dieReadOnly() {
1153 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1154 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1155 array( 'readonlyreason' => wfReadOnlyReason() ) );
1159 * Output the error message related to a certain array
1160 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1162 public function dieUsageMsg( $error ) {
1163 # most of the time we send a 1 element, so we might as well send it as
1164 # a string and make this an array here.
1165 if( is_string( $error ) ) {
1166 $error = array( $error );
1168 $parsed = $this->parseMsg( $error );
1169 $this->dieUsage( $parsed['info'], $parsed['code'] );
1173 * Return the error message related to a certain array
1174 * @param $error array Element of a getUserPermissionsErrors()-style array
1175 * @return array('code' => code, 'info' => info)
1177 public function parseMsg( $error ) {
1178 $key = array_shift( $error );
1180 // Check whether the error array was nested
1181 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1182 if( is_array( $key ) ){
1184 $key = array_shift( $error );
1187 if ( isset( self
::$messageMap[$key] ) ) {
1188 return array( 'code' =>
1189 wfMsgReplaceArgs( self
::$messageMap[$key]['code'], $error ),
1191 wfMsgReplaceArgs( self
::$messageMap[$key]['info'], $error )
1195 // If the key isn't present, throw an "unknown error"
1196 return $this->parseMsg( array( 'unknownerror', $key ) );
1200 * Internal code errors should be reported with this method
1201 * @param $method string Method or function name
1202 * @param $message string Error message
1204 protected static function dieDebug( $method, $message ) {
1205 wfDebugDieBacktrace( "Internal error in $method: $message" );
1209 * Indicates if this module needs maxlag to be checked
1212 public function shouldCheckMaxlag() {
1217 * Indicates whether this module requires read rights
1220 public function isReadMode() {
1224 * Indicates whether this module requires write mode
1227 public function isWriteMode() {
1232 * Indicates whether this module must be called with a POST request
1235 public function mustBePosted() {
1240 * Returns whether this module requires a Token to execute
1243 public function needsToken() {
1248 * 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
1251 public function getTokenSalt() {
1256 * Gets the user for whom to get the watchlist
1258 * @param $params array
1261 public function getWatchlistUser( $params ) {
1263 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1264 $user = User
::newFromName( $params['owner'], false );
1265 if ( !$user->getId() ) {
1266 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1268 $token = $user->getOption( 'watchlisttoken' );
1269 if ( $token == '' ||
$token != $params['token'] ) {
1270 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1273 if ( !$wgUser->isLoggedIn() ) {
1274 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1282 * Returns a list of all possible errors returned by the module
1283 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1285 public function getPossibleErrors() {
1288 $params = $this->getFinalParams();
1290 foreach ( $params as $paramName => $paramSettings ) {
1291 if ( isset( $paramSettings[ApiBase
::PARAM_REQUIRED
] ) ) {
1292 $ret[] = array( 'missingparam', $paramName );
1297 if ( $this->mustBePosted() ) {
1298 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1301 if ( $this->isReadMode() ) {
1302 $ret[] = array( 'readrequired' );
1305 if ( $this->isWriteMode() ) {
1306 $ret[] = array( 'writerequired' );
1307 $ret[] = array( 'writedisabled' );
1310 if ( $this->needsToken() ) {
1311 $ret[] = array( 'missingparam', 'token' );
1312 $ret[] = array( 'sessionfailure' );
1319 * Parses a list of errors into a standardised format
1320 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1321 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1323 public function parseErrors( $errors ) {
1326 foreach ( $errors as $row ) {
1327 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1330 $ret[] = $this->parseMsg( $row );
1337 * Profiling: total module execution time
1339 private $mTimeIn = 0, $mModuleTime = 0;
1342 * Start module profiling
1344 public function profileIn() {
1345 if ( $this->mTimeIn
!== 0 ) {
1346 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileOut()' );
1348 $this->mTimeIn
= microtime( true );
1349 wfProfileIn( $this->getModuleProfileName() );
1353 * End module profiling
1355 public function profileOut() {
1356 if ( $this->mTimeIn
=== 0 ) {
1357 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileIn() first' );
1359 if ( $this->mDBTimeIn
!== 0 ) {
1360 ApiBase
::dieDebug( __METHOD__
, 'must be called after database profiling is done with profileDBOut()' );
1363 $this->mModuleTime +
= microtime( true ) - $this->mTimeIn
;
1365 wfProfileOut( $this->getModuleProfileName() );
1369 * When modules crash, sometimes it is needed to do a profileOut() regardless
1370 * of the profiling state the module was in. This method does such cleanup.
1372 public function safeProfileOut() {
1373 if ( $this->mTimeIn
!== 0 ) {
1374 if ( $this->mDBTimeIn
!== 0 ) {
1375 $this->profileDBOut();
1377 $this->profileOut();
1382 * Total time the module was executed
1385 public function getProfileTime() {
1386 if ( $this->mTimeIn
!== 0 ) {
1387 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileOut() first' );
1389 return $this->mModuleTime
;
1393 * Profiling: database execution time
1395 private $mDBTimeIn = 0, $mDBTime = 0;
1398 * Start module profiling
1400 public function profileDBIn() {
1401 if ( $this->mTimeIn
=== 0 ) {
1402 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1404 if ( $this->mDBTimeIn
!== 0 ) {
1405 ApiBase
::dieDebug( __METHOD__
, 'called twice without calling profileDBOut()' );
1407 $this->mDBTimeIn
= microtime( true );
1408 wfProfileIn( $this->getModuleProfileName( true ) );
1412 * End database profiling
1414 public function profileDBOut() {
1415 if ( $this->mTimeIn
=== 0 ) {
1416 ApiBase
::dieDebug( __METHOD__
, 'must be called while profiling the entire module with profileIn()' );
1418 if ( $this->mDBTimeIn
=== 0 ) {
1419 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBIn() first' );
1422 $time = microtime( true ) - $this->mDBTimeIn
;
1423 $this->mDBTimeIn
= 0;
1425 $this->mDBTime +
= $time;
1426 $this->getMain()->mDBTime +
= $time;
1427 wfProfileOut( $this->getModuleProfileName( true ) );
1431 * Total time the module used the database
1434 public function getProfileDBTime() {
1435 if ( $this->mDBTimeIn
!== 0 ) {
1436 ApiBase
::dieDebug( __METHOD__
, 'called without calling profileDBOut() first' );
1438 return $this->mDBTime
;
1442 * Debugging function that prints a value and an optional backtrace
1443 * @param $value mixed Value to print
1444 * @param $name string Description of the printed value
1445 * @param $backtrace bool If true, print a backtrace
1447 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1448 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1449 var_export( $value );
1451 print "\n" . wfBacktrace();
1457 * Returns a string that identifies the version of this class.
1460 public static function getBaseVersion() {
1461 return __CLASS__
. ': $Id$';