4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006, 2010 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
27 * This abstract class implements many basic API functions, and is the base of
29 * The class functions are divided into several areas of functionality:
31 * Module parameters: Derived classes can define getAllowedParams() to specify
32 * which parameters to expect,h ow to parse and validate them.
34 * Profiling: various methods to allow keeping tabs on various tasks and their
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase {
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 const PARAM_DFLT = 0; // Default value of the parameter
46 const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
47 const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
48 const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
49 const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
50 const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
51 const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
52 const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
54 const LIMIT_BIG1 = 500; // Fast query, std user limit
55 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
56 const LIMIT_SML1 = 50; // Slow query, std user limit
57 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
59 private $mMainModule, $mModuleName, $mModulePrefix;
60 private $mParamCache = array();
64 * @param $mainModule ApiMain object
65 * @param $moduleName string Name of this module
66 * @param $modulePrefix string Prefix to use for parameter names
68 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
69 $this->mMainModule = $mainModule;
70 $this->mModuleName = $moduleName;
71 $this->mModulePrefix = $modulePrefix;
74 /*****************************************************************************
76 *****************************************************************************/
79 * Evaluates the parameters, performs the requested query, and sets up
80 * the result. Concrete implementations of ApiBase must override this
81 * method to provide whatever functionality their module offers.
82 * Implementations must not produce any output on their own and are not
83 * expected to handle any errors.
85 * The execute() method will be invoked directly by ApiMain immediately
86 * before the result of the module is output. Aside from the
87 * constructor, implementations should assume that no other methods
88 * will be called externally on the module before the result is
91 * The result data should be stored in the ApiResult object available
92 * through getResult().
94 public abstract function execute();
97 * Returns a string that identifies the version of the extending class.
98 * Typically includes the class name, the svn revision, timestamp, and
99 * last author. Usually done with SVN's Id keyword
102 public abstract function getVersion();
105 * Get the name of the module being executed by this instance
108 public function getModuleName() {
109 return $this->mModuleName;
113 * Get parameter prefix (usually two letters or an empty string).
116 public function getModulePrefix() {
117 return $this->mModulePrefix;
121 * Get the name of the module as shown in the profiler log
124 public function getModuleProfileName( $db = false ) {
126 return 'API:' . $this->mModuleName . '-DB';
128 return 'API:' . $this->mModuleName;
133 * Get the main module
134 * @return ApiMain object
136 public function getMain() {
137 return $this->mMainModule;
141 * Returns true if this module is the main module ($this === $this->mMainModule),
145 public function isMain() {
146 return $this === $this->mMainModule;
150 * Get the result object
153 public function getResult() {
154 // Main module has getResult() method overriden
155 // Safety - avoid infinite loop:
156 if ( $this->isMain() ) {
157 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
159 return $this->getMain()->getResult();
163 * Get the result data array (read-only)
166 public function getResultData() {
167 return $this->getResult()->getData();
171 * Set warning section for this module. Users should monitor this
172 * section to notice any changes in API. Multiple calls to this
173 * function will result in the warning messages being separated by
175 * @param $warning string Warning message
177 public function setWarning( $warning ) {
178 $data = $this->getResult()->getData();
179 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
180 // Don't add duplicate warnings
181 $warn_regex = preg_quote( $warning, '/' );
182 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) )
186 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
187 // If there is a warning already, append it to the existing one
188 $warning = "$oldwarning\n$warning";
189 $this->getResult()->unsetValue( 'warnings', $this->getModuleName() );
192 ApiResult::setContent( $msg, $warning );
193 $this->getResult()->disableSizeCheck();
194 $this->getResult()->addValue( 'warnings', $this->getModuleName(), $msg );
195 $this->getResult()->enableSizeCheck();
199 * If the module may only be used with a certain format module,
200 * it should override this method to return an instance of that formatter.
201 * A value of null means the default format will be used.
202 * @return mixed instance of a derived class of ApiFormatBase, or null
204 public function getCustomPrinter() {
209 * Generates help message for this module, or false if there is no description
210 * @return mixed string or false
212 public function makeHelpMsg() {
213 static $lnPrfx = "\n ";
215 $msg = $this->getDescription();
217 if ( $msg !== false ) {
219 if ( !is_array( $msg ) ) {
224 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
226 if ( $this->isReadMode() ) {
227 $msg .= "\nThis module requires read rights.";
229 if ( $this->isWriteMode() ) {
230 $msg .= "\nThis module requires write rights.";
232 if ( $this->mustBePosted() ) {
233 $msg .= "\nThis module only accepts POST requests.";
235 if ( $this->isReadMode() || $this->isWriteMode() ||
236 $this->mustBePosted() )
242 $paramsMsg = $this->makeHelpMsgParameters();
243 if ( $paramsMsg !== false ) {
244 $msg .= "Parameters:\n$paramsMsg";
248 $examples = $this->getExamples();
249 if ( $examples !== false ) {
250 if ( !is_array( $examples ) ) {
255 $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n ";
256 $msg .= implode( $lnPrfx, $examples ) . "\n";
259 if ( $this->getMain()->getShowVersions() ) {
260 $versions = $this->getVersion();
261 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
262 $callback = array( $this, 'makeHelpMsg_callback' );
264 if ( is_array( $versions ) ) {
265 foreach ( $versions as &$v ) {
266 $v = preg_replace_callback( $pattern, $callback, $v );
268 $versions = implode( "\n ", $versions );
270 $versions = preg_replace_callback( $pattern, $callback, $versions );
273 $msg .= "Version:\n $versions\n";
281 * Generates the parameter descriptions for this module, to be displayed in the
285 public function makeHelpMsgParameters() {
286 $params = $this->getFinalParams();
289 $paramsDescription = $this->getFinalParamDescription();
291 $paramPrefix = "\n" . str_repeat( ' ', 19 );
292 foreach ( $params as $paramName => $paramSettings ) {
293 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
294 if ( is_array( $desc ) ) {
295 $desc = implode( $paramPrefix, $desc );
298 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ?
299 $paramSettings[self::PARAM_DEPRECATED] : false;
301 $desc = "DEPRECATED! $desc";
304 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
305 if ( isset( $type ) ) {
306 if ( isset( $paramSettings[self::PARAM_ISMULTI] ) ) {
307 $prompt = 'Values (separate with \'|\'): ';
309 $prompt = 'One value: ';
312 if ( is_array( $type ) ) {
314 $nothingPrompt = false;
315 foreach ( $type as $t )
317 $nothingPrompt = 'Can be empty, or ';
321 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode( ', ', $choices );
325 // Special handling because namespaces are type-limited, yet they are not given
326 $desc .= $paramPrefix . $prompt . implode( ', ', ApiBase::getValidNamespaces() );
329 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self::PARAM_MAX2]} for bots) allowed.";
332 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
333 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
334 if ( $hasMin || $hasMax ) {
336 $intRangeStr = "The value must be no less than {$paramSettings[self::PARAM_MIN]}";
337 } elseif ( !$hasMin ) {
338 $intRangeStr = "The value must be no more than {$paramSettings[self::PARAM_MAX]}";
340 $intRangeStr = "The value must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
343 $desc .= $paramPrefix . $intRangeStr;
350 $default = is_array( $paramSettings ) ? ( isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null ) : $paramSettings;
351 if ( !is_null( $default ) && $default !== false ) {
352 $desc .= $paramPrefix . "Default: $default";
355 $msg .= sprintf( " %-14s - %s\n", $this->encodeParamName( $paramName ), $desc );
365 * Callback for preg_replace_callback() call in makeHelpMsg().
366 * Replaces a source file name with a link to ViewVC
368 public function makeHelpMsg_callback( $matches ) {
369 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
370 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
371 $file = $wgAutoloadLocalClasses[get_class( $this )];
372 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
373 $file = $wgAutoloadClasses[get_class( $this )];
376 // Do some guesswork here
377 $path = strstr( $file, 'includes/api/' );
378 if ( $path === false ) {
379 $path = strstr( $file, 'extensions/' );
381 $path = 'phase3/' . $path;
384 // Get the filename from $matches[2] instead of $file
385 // If they're not the same file, they're assumed to be in the
387 // This is necessary to make stuff like ApiMain::getVersion()
388 // returning the version string for ApiBase work
390 return "{$matches[0]}\n http://svn.wikimedia.org/" .
391 "viewvc/mediawiki/trunk/" . dirname( $path ) .
398 * Returns the description string for this module
399 * @return mixed string or array of strings
401 protected function getDescription() {
406 * Returns usage examples for this module. Return null if no examples are available.
407 * @return mixed string or array of strings
409 protected function getExamples() {
414 * Returns an array of allowed parameters (parameter name) => (default
415 * value) or (parameter name) => (array with PARAM_* constants as keys)
416 * Don't call this function directly: use getFinalParams() to allow
417 * hooks to modify parameters as needed.
420 protected function getAllowedParams() {
425 * Returns an array of parameter descriptions.
426 * Don't call this functon directly: use getFinalParamDescription() to
427 * allow hooks to modify descriptions as needed.
430 protected function getParamDescription() {
435 * Get final list of parameters, after hooks have had a chance to
436 * tweak it as needed.
439 public function getFinalParams() {
440 $params = $this->getAllowedParams();
441 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
446 * Get final description, after hooks have had a chance to tweak it as
450 public function getFinalParamDescription() {
451 $desc = $this->getParamDescription();
452 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
457 * This method mangles parameter name based on the prefix supplied to the constructor.
458 * Override this method to change parameter name during runtime
459 * @param $paramName string Parameter name
460 * @return string Prefixed parameter name
462 public function encodeParamName( $paramName ) {
463 return $this->mModulePrefix . $paramName;
467 * Using getAllowedParams(), this function makes an array of the values
468 * provided by the user, with key being the name of the variable, and
469 * value - validated value from user or default. limits will not be
470 * parsed if $parseLimit is set to false; use this when the max
471 * limit is not definitive yet, e.g. when getting revisions.
472 * @param $parseLimit Boolean: true by default
475 public function extractRequestParams( $parseLimit = true ) {
476 // Cache parameters, for performance and to avoid bug 24564.
477 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
478 $params = $this->getFinalParams();
481 if ( $params ) { // getFinalParams() can return false
482 foreach ( $params as $paramName => $paramSettings ) {
483 $results[$paramName] = $this->getParameterFromSettings(
484 $paramName, $paramSettings, $parseLimit );
487 $this->mParamCache[$parseLimit] = $results;
489 return $this->mParamCache[$parseLimit];
493 * Get a value for the given parameter
494 * @param $paramName string Parameter name
495 * @param $parseLimit bool see extractRequestParams()
496 * @return mixed Parameter value
498 protected function getParameter( $paramName, $parseLimit = true ) {
499 $params = $this->getFinalParams();
500 $paramSettings = $params[$paramName];
501 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
505 * Die if none or more than one of a certain set of parameters is set and not false.
506 * @param $params array of parameter names
508 public function requireOnlyOneParameter( $params ) {
509 $required = func_get_args();
510 array_shift( $required );
512 $intersection = array_intersect( array_keys( array_filter( $params,
513 create_function( '$x', 'return !is_null($x) && $x !== false;' )
515 if ( count( $intersection ) > 1 ) {
516 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
517 } elseif ( count( $intersection ) == 0 ) {
518 $this->dieUsage( 'One of the parameters ' . implode( ', ', $required ) . ' is required', 'missingparam' );
523 * Returns an array of the namespaces (by integer id) that exist on the
524 * wiki. Used primarily in help documentation.
527 public static function getValidNamespaces() {
528 static $mValidNamespaces = null;
530 if ( is_null( $mValidNamespaces ) ) {
532 $mValidNamespaces = array();
533 foreach ( array_keys( $wgContLang->getNamespaces() ) as $ns ) {
535 $mValidNamespaces[] = $ns;
540 return $mValidNamespaces;
544 * Using the settings determine the value for the given parameter
546 * @param $paramName String: parameter name
547 * @param $paramSettings Mixed: default value or an array of settings
548 * using PARAM_* constants.
549 * @param $parseLimit Boolean: parse limit?
550 * @return mixed Parameter value
552 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
553 // Some classes may decide to change parameter names
554 $encParamName = $this->encodeParamName( $paramName );
556 if ( !is_array( $paramSettings ) ) {
557 $default = $paramSettings;
559 $type = gettype( $paramSettings );
563 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
564 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
565 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
566 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
567 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
569 // When type is not given, and no choices, the type is the same as $default
570 if ( !isset( $type ) ) {
571 if ( isset( $default ) ) {
572 $type = gettype( $default );
574 $type = 'NULL'; // allow everything
579 if ( $type == 'boolean' ) {
580 if ( isset( $default ) && $default !== false ) {
581 // Having a default value of anything other than 'false' is pointless
582 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'" );
585 $value = $this->getMain()->getRequest()->getCheck( $encParamName );
587 $value = $this->getMain()->getRequest()->getVal( $encParamName, $default );
589 if ( isset( $value ) && $type == 'namespace' ) {
590 $type = ApiBase::getValidNamespaces();
594 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
595 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
598 // More validation only when choices were not given
599 // choices were validated in parseMultiValue()
600 if ( isset( $value ) ) {
601 if ( !is_array( $type ) ) {
603 case 'NULL': // nothing to do
605 case 'string': // nothing to do
607 case 'integer': // Force everything using intval() and optionally validate limits
609 $value = is_array( $value ) ? array_map( 'intval', $value ) : intval( $value );
610 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
611 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
613 if ( !is_null( $min ) || !is_null( $max ) ) {
614 $values = is_array( $value ) ? $value : array( $value );
615 foreach ( $values as &$v ) {
616 $this->validateLimit( $paramName, $v, $min, $max );
621 if ( !$parseLimit ) {
622 // Don't do any validation whatsoever
625 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
626 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
629 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
631 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
632 if ( $value == 'max' ) {
633 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
634 $this->getResult()->addValue( 'limits', $this->getModuleName(), $value );
636 $value = intval( $value );
637 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
642 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
646 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
648 $value = wfTimestamp( TS_UNIX, $value );
649 if ( $value === 0 ) {
650 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
652 $value = wfTimestamp( TS_MW, $value );
655 $title = Title::makeTitleSafe( NS_USER, $value );
656 if ( is_null( $title ) ) {
657 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
659 $value = $title->getText();
662 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
666 // Throw out duplicates if requested
667 if ( is_array( $value ) && !$dupes ) {
668 $value = array_unique( $value );
671 // Set a warning if a deprecated parameter has been passed
672 if ( $deprecated && $value !== false ) {
673 $this->setWarning( "The $encParamName parameter has been deprecated." );
681 * Return an array of values that were given in a 'a|b|c' notation,
682 * after it optionally validates them against the list allowed values.
684 * @param $valueName string The name of the parameter (for error
686 * @param $value mixed The value being parsed
687 * @param $allowMultiple bool Can $value contain more than one value
689 * @param $allowedValues mixed An array of values to check against. If
690 * null, all values are accepted.
691 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
693 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
694 if ( trim( $value ) === '' && $allowMultiple ) {
698 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
699 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
700 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
701 self::LIMIT_SML2 : self::LIMIT_SML1;
703 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
704 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
707 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
708 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
709 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
712 if ( is_array( $allowedValues ) ) {
713 // Check for unknown values
714 $unknown = array_diff( $valuesList, $allowedValues );
715 if ( count( $unknown ) ) {
716 if ( $allowMultiple ) {
717 $s = count( $unknown ) > 1 ? 's' : '';
718 $vals = implode( ", ", $unknown );
719 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
721 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
724 // Now throw them out
725 $valuesList = array_intersect( $valuesList, $allowedValues );
728 return $allowMultiple ? $valuesList : $valuesList[0];
732 * Validate the value against the minimum and user/bot maximum limits.
733 * Prints usage info on failure.
734 * @param $paramName string Parameter name
735 * @param $value int Parameter value
736 * @param $min int Minimum value
737 * @param $max int Maximum value for users
738 * @param $botMax int Maximum value for sysops/bots
740 function validateLimit( $paramName, &$value, $min, $max, $botMax = null ) {
741 if ( !is_null( $min ) && $value < $min ) {
742 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)" );
746 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
747 if ( $this->getMain()->isInternalMode() ) {
751 // Optimization: do not check user's bot status unless really needed -- skips db query
752 // assumes $botMax >= $max
753 if ( !is_null( $max ) && $value > $max ) {
754 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
755 if ( $value > $botMax ) {
756 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops" );
760 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users" );
767 * Truncate an array to a certain length.
768 * @param $arr array Array to truncate
769 * @param $limit int Maximum length
770 * @return bool True if the array was truncated, false otherwise
772 public static function truncateArray( &$arr, $limit ) {
774 while ( count( $arr ) > $limit ) {
775 $junk = array_pop( $arr );
782 * Throw a UsageException, which will (if uncaught) call the main module's
783 * error handler and die with an error message.
785 * @param $description string One-line human-readable description of the
786 * error condition, e.g., "The API requires a valid action parameter"
787 * @param $errorCode string Brief, arbitrary, stable string to allow easy
788 * automated identification of the error, e.g., 'unknown_action'
789 * @param $httpRespCode int HTTP response code
790 * @param $extradata array Data to add to the <error> element; array in ApiResult format
792 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
794 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
798 * Array that maps message keys to error messages. $1 and friends are replaced.
800 public static $messageMap = array(
801 // This one MUST be present, or dieUsageMsg() will recurse infinitely
802 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: ``\$1''" ),
803 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
805 // Messages from Title::getUserPermissionsErrors()
806 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
807 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
808 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace" ),
809 'customcssjsprotected' => array( 'code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages" ),
810 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
811 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page" ),
812 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
813 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
814 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
815 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
816 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
817 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
818 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
819 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
820 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
821 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
822 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
824 // Miscellaneous interface messages
825 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
826 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
827 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
828 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
829 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
830 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else" ),
831 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
832 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
833 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
834 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
835 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
836 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
837 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
838 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
839 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
840 // 'badarticleerror' => shouldn't happen
841 // 'badtitletext' => shouldn't happen
842 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
843 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
844 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
845 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
846 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
847 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
848 '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." ),
849 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
850 '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" ),
851 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
852 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
853 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
854 '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" ),
855 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
856 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
857 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
858 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
859 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
860 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database ``\$1'' does not exist or is not local" ),
861 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
862 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
864 // API-specific messages
865 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
866 '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" ),
867 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
868 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
869 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title ``\$1''" ),
870 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
871 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
872 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User ``\$1'' doesn't exist" ),
873 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
874 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''" ),
875 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past" ),
876 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
877 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
878 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
879 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
880 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
881 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
882 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
883 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
884 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
885 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
886 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
887 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
888 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''" ),
889 'cantpurge' => array( 'code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API" ),
890 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''" ),
891 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''" ),
892 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
893 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
894 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
895 'nouploadmodule' => array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
896 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
897 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
898 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
899 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
900 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
901 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
902 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
903 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: ``\$1''" ),
904 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
905 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
906 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
907 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
909 // ApiEditPage messages
910 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
911 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
912 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''" ),
913 'filtered' => array( 'code' => 'filtered', 'info' => "The filter callback function refused your edit" ),
914 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
915 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
916 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
917 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
918 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
919 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
920 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
921 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
922 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
923 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of ``\$2''" ),
924 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
927 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ),
928 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
929 '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' ),
933 * Helper function for readonly errors
935 public function dieReadOnly() {
936 $parsed = $this->parseMsg( array( 'readonlytext' ) );
937 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
938 array( 'readonlyreason' => wfReadOnlyReason() ) );
942 * Output the error message related to a certain array
943 * @param $error array Element of a getUserPermissionsErrors()-style array
945 public function dieUsageMsg( $error ) {
946 $parsed = $this->parseMsg( $error );
947 $this->dieUsage( $parsed['info'], $parsed['code'] );
951 * Return the error message related to a certain array
952 * @param $error array Element of a getUserPermissionsErrors()-style array
953 * @return array('code' => code, 'info' => info)
955 public function parseMsg( $error ) {
956 $key = array_shift( $error );
957 if ( isset( self::$messageMap[$key] ) ) {
958 return array( 'code' =>
959 wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
961 wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
964 // If the key isn't present, throw an "unknown error"
965 return $this->parseMsg( array( 'unknownerror', $key ) );
969 * Internal code errors should be reported with this method
970 * @param $method string Method or function name
971 * @param $message string Error message
973 protected static function dieDebug( $method, $message ) {
974 wfDebugDieBacktrace( "Internal error in $method: $message" );
978 * Indicates if this module needs maxlag to be checked
981 public function shouldCheckMaxlag() {
986 * Indicates whether this module requires read rights
989 public function isReadMode() {
993 * Indicates whether this module requires write mode
996 public function isWriteMode() {
1001 * Indicates whether this module must be called with a POST request
1004 public function mustBePosted() {
1009 * Returns whether this module requires a Token to execute
1012 public function needsToken() {
1017 * 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
1020 public function getTokenSalt() {
1025 * Returns a list of all possible errors returned by the module
1026 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1028 public function getPossibleErrors() {
1031 if ( $this->mustBePosted() ) {
1032 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1035 if ( $this->isReadMode() ) {
1036 $ret[] = array( 'readrequired' );
1039 if ( $this->isWriteMode() ) {
1040 $ret[] = array( 'writerequired' );
1041 $ret[] = array( 'writedisabled' );
1044 if ( $this->needsToken() ) {
1045 $ret[] = array( 'missingparam', 'token' );
1046 $ret[] = array( 'sessionfailure' );
1053 * Parses a list of errors into a standardised format
1054 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1055 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1057 public function parseErrors( $errors ) {
1060 foreach ( $errors as $row ) {
1061 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1064 $ret[] = $this->parseMsg( $row );
1071 * Profiling: total module execution time
1073 private $mTimeIn = 0, $mModuleTime = 0;
1076 * Start module profiling
1078 public function profileIn() {
1079 if ( $this->mTimeIn !== 0 ) {
1080 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
1082 $this->mTimeIn = microtime( true );
1083 wfProfileIn( $this->getModuleProfileName() );
1087 * End module profiling
1089 public function profileOut() {
1090 if ( $this->mTimeIn === 0 ) {
1091 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
1093 if ( $this->mDBTimeIn !== 0 ) {
1094 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
1097 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
1099 wfProfileOut( $this->getModuleProfileName() );
1103 * When modules crash, sometimes it is needed to do a profileOut() regardless
1104 * of the profiling state the module was in. This method does such cleanup.
1106 public function safeProfileOut() {
1107 if ( $this->mTimeIn !== 0 ) {
1108 if ( $this->mDBTimeIn !== 0 ) {
1109 $this->profileDBOut();
1111 $this->profileOut();
1116 * Total time the module was executed
1119 public function getProfileTime() {
1120 if ( $this->mTimeIn !== 0 ) {
1121 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
1123 return $this->mModuleTime;
1127 * Profiling: database execution time
1129 private $mDBTimeIn = 0, $mDBTime = 0;
1132 * Start module profiling
1134 public function profileDBIn() {
1135 if ( $this->mTimeIn === 0 ) {
1136 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1138 if ( $this->mDBTimeIn !== 0 ) {
1139 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
1141 $this->mDBTimeIn = microtime( true );
1142 wfProfileIn( $this->getModuleProfileName( true ) );
1146 * End database profiling
1148 public function profileDBOut() {
1149 if ( $this->mTimeIn === 0 ) {
1150 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1152 if ( $this->mDBTimeIn === 0 ) {
1153 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
1156 $time = microtime( true ) - $this->mDBTimeIn;
1157 $this->mDBTimeIn = 0;
1159 $this->mDBTime += $time;
1160 $this->getMain()->mDBTime += $time;
1161 wfProfileOut( $this->getModuleProfileName( true ) );
1165 * Total time the module used the database
1168 public function getProfileDBTime() {
1169 if ( $this->mDBTimeIn !== 0 ) {
1170 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
1172 return $this->mDBTime;
1176 * Debugging function that prints a value and an optional backtrace
1177 * @param $value mixed Value to print
1178 * @param $name string Description of the printed value
1179 * @param $backtrace bool If true, print a backtrace
1181 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1182 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1183 var_export( $value );
1185 print "\n" . wfBacktrace();
1191 * Returns a string that identifies the version of this class.
1194 public static function getBaseVersion() {
1195 return __CLASS__ . ': $Id: ApiBase.php 79562 2011-01-04 06:15:54Z tstarling $';