4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 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 all API classes.
28 * The class functions are divided into several areas of functionality:
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
35 * Self-documentation: code to allow api to document its own state.
39 abstract class ApiBase
{
41 // These constants allow modules to specify exactly how to treat incomming parameters.
44 const PARAM_ISMULTI
= 1;
50 const LIMIT_BIG1
= 500; // Fast query, std user limit
51 const LIMIT_BIG2
= 5000; // Fast query, bot/sysop limit
52 const LIMIT_SML1
= 50; // Slow query, std user limit
53 const LIMIT_SML2
= 500; // Slow query, bot/sysop limit
55 private $mMainModule, $mModuleName, $mModulePrefix;
60 public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61 $this->mMainModule
= $mainModule;
62 $this->mModuleName
= $moduleName;
63 $this->mModulePrefix
= $modulePrefix;
67 * Executes this module
69 public abstract function execute();
72 * Get the name of the module being executed by this instance
74 public function getModuleName() {
75 return $this->mModuleName
;
79 * Get parameter prefix (usually two letters or an empty string).
81 public function getModulePrefix() {
82 return $this->mModulePrefix
;
86 * Get the name of the module as shown in the profiler log
88 public function getModuleProfileName($db = false) {
90 return 'API:' . $this->mModuleName
. '-DB';
92 return 'API:' . $this->mModuleName
;
98 public function getMain() {
99 return $this->mMainModule
;
103 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
105 public function isMain() {
106 return $this === $this->mMainModule
;
112 public function getResult() {
113 // Main module has getResult() method overriden
114 // Safety - avoid infinite loop:
116 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
117 return $this->getMain()->getResult();
121 * Get the result data array
123 public function & getResultData() {
124 return $this->getResult()->getData();
128 * Set warning section for this module. Users should monitor this section to notice any changes in API.
130 public function setWarning($warning) {
132 ApiResult
:: setContent($msg, $warning);
133 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
137 * If the module may only be used with a certain format module,
138 * it should override this method to return an instance of that formatter.
139 * A value of null means the default format will be used.
141 public function getCustomPrinter() {
146 * Generates help message for this module, or false if there is no description
148 public function makeHelpMsg() {
150 static $lnPrfx = "\n ";
152 $msg = $this->getDescription();
154 if ($msg !== false) {
160 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
163 $paramsMsg = $this->makeHelpMsgParameters();
164 if ($paramsMsg !== false) {
165 $msg .= "Parameters:\n$paramsMsg";
169 $examples = $this->getExamples();
170 if ($examples !== false) {
171 if (!is_array($examples))
175 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
176 $msg .= implode($lnPrfx, $examples) . "\n";
179 if ($this->getMain()->getShowVersions()) {
180 $versions = $this->getVersion();
181 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
182 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
184 if (is_array($versions)) {
185 foreach ($versions as &$v)
186 $v = eregi_replace($pattern, $replacement, $v);
187 $versions = implode("\n ", $versions);
190 $versions = eregi_replace($pattern, $replacement, $versions);
192 $msg .= "Version:\n $versions\n";
199 public function makeHelpMsgParameters() {
200 $params = $this->getAllowedParams();
201 if ($params !== false) {
203 $paramsDescription = $this->getParamDescription();
205 $paramPrefix = "\n" . str_repeat(' ', 19);
206 foreach ($params as $paramName => $paramSettings) {
207 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
209 $desc = implode($paramPrefix, $desc);
211 @ $type = $paramSettings[self
:: PARAM_TYPE
];
213 if (isset ($paramSettings[self
:: PARAM_ISMULTI
]))
214 $prompt = 'Values (separate with \'|\'): ';
216 $prompt = 'One value: ';
218 if (is_array($type)) {
220 $nothingPrompt = false;
221 foreach ($type as $t)
223 $nothingPrompt = 'Can be empty, or ';
226 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
230 // Special handling because namespaces are type-limited, yet they are not given
231 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase
:: getValidNamespaces());
234 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
237 $hasMin = isset($paramSettings[self
:: PARAM_MIN
]);
238 $hasMax = isset($paramSettings[self
:: PARAM_MAX
]);
239 if ($hasMin ||
$hasMax) {
241 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
243 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
245 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
247 $desc .= $paramPrefix . $intRangeStr;
254 $default = is_array($paramSettings) ?
(isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null) : $paramSettings;
255 if (!is_null($default) && $default !== false)
256 $desc .= $paramPrefix . "Default: $default";
258 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
267 * Returns the description string for this module
269 protected function getDescription() {
274 * Returns usage examples for this module. Return null if no examples are available.
276 protected function getExamples() {
281 * Returns an array of allowed parameters (keys) => default value for that parameter
283 protected function getAllowedParams() {
288 * Returns the description string for the given parameter.
290 protected function getParamDescription() {
295 * This method mangles parameter name based on the prefix supplied to the constructor.
296 * Override this method to change parameter name during runtime
298 public function encodeParamName($paramName) {
299 return $this->mModulePrefix
. $paramName;
303 * Using getAllowedParams(), makes an array of the values provided by the user,
304 * with key being the name of the variable, and value - validated value from user or default.
305 * This method can be used to generate local variables using extract().
307 public function extractRequestParams() {
308 $params = $this->getAllowedParams();
311 foreach ($params as $paramName => $paramSettings)
312 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
318 * Get a value for the given parameter
320 protected function getParameter($paramName) {
321 $params = $this->getAllowedParams();
322 $paramSettings = $params[$paramName];
323 return $this->getParameterFromSettings($paramName, $paramSettings);
326 public static function getValidNamespaces() {
327 static $mValidNamespaces = null;
328 if (is_null($mValidNamespaces)) {
331 $mValidNamespaces = array ();
332 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
334 $mValidNamespaces[] = $ns;
337 return $mValidNamespaces;
341 * Using the settings determine the value for the given parameter
342 * @param $paramName String: parameter name
343 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
345 protected function getParameterFromSettings($paramName, $paramSettings) {
347 // Some classes may decide to change parameter names
348 $encParamName = $this->encodeParamName($paramName);
350 if (!is_array($paramSettings)) {
351 $default = $paramSettings;
353 $type = gettype($paramSettings);
355 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
356 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
357 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
359 // When type is not given, and no choices, the type is the same as $default
360 if (!isset ($type)) {
361 if (isset ($default))
362 $type = gettype($default);
364 $type = 'NULL'; // allow everything
368 if ($type == 'boolean') {
369 if (isset ($default) && $default !== false) {
370 // Having a default value of anything other than 'false' is pointless
371 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $encParamName's default is set to '$default'");
374 $value = $this->getMain()->getRequest()->getCheck($encParamName);
376 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
378 if (isset ($value) && $type == 'namespace')
379 $type = ApiBase
:: getValidNamespaces();
382 if (isset ($value) && ($multi ||
is_array($type)))
383 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ?
$type : null);
385 // More validation only when choices were not given
386 // choices were validated in parseMultiValue()
387 if (isset ($value)) {
388 if (!is_array($type)) {
390 case 'NULL' : // nothing to do
392 case 'string' : // nothing to do
394 case 'integer' : // Force everything using intval() and optionally validate limits
396 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
397 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : null;
398 $max = isset ($paramSettings[self
:: PARAM_MAX
]) ?
$paramSettings[self
:: PARAM_MAX
] : null;
400 if (!is_null($min) ||
!is_null($max)) {
401 $values = is_array($value) ?
$value : array($value);
402 foreach ($values as $v) {
403 $this->validateLimit($paramName, $v, $min, $max);
408 if (!isset ($paramSettings[self
:: PARAM_MAX
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
409 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $encParamName");
411 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $encParamName");
412 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
413 $value = intval($value);
414 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX
], $paramSettings[self
:: PARAM_MAX2
]);
418 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $encParamName");
422 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $encParamName");
423 $value = wfTimestamp(TS_UNIX
, $value);
425 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
426 $value = wfTimestamp(TS_MW
, $value);
429 $title = Title
::makeTitleSafe( NS_USER
, $value );
430 if ( is_null( $title ) )
431 $this->dieUsage("Invalid value $user for user parameter $encParamName", "baduser_{$encParamName}");
432 $value = $title->getText();
435 ApiBase
:: dieDebug(__METHOD__
, "Param $encParamName's type is unknown - $type");
439 // There should never be any duplicate values in a list
440 if (is_array($value))
441 $value = array_unique($value);
448 * Return an array of values that were given in a 'a|b|c' notation,
449 * after it optionally validates them against the list allowed values.
451 * @param valueName - The name of the parameter (for error reporting)
452 * @param value - The value being parsed
453 * @param allowMultiple - Can $value contain more than one value separated by '|'?
454 * @param allowedValues - An array of values to check against. If null, all values are accepted.
455 * @return (allowMultiple ? an_array_of_values : a_single_value)
457 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
458 $valuesList = explode('|', $value);
459 if (!$allowMultiple && count($valuesList) != 1) {
460 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
461 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
463 if (is_array($allowedValues)) {
464 $unknownValues = array_diff($valuesList, $allowedValues);
465 if ($unknownValues) {
466 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s" : "") . " for parameter '$valueName'", "unknown_$valueName");
470 return $allowMultiple ?
$valuesList : $valuesList[0];
474 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
476 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
477 if (!is_null($min) && $value < $min) {
478 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
481 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
482 if ($this->getMain()->isInternalMode())
485 // Optimization: do not check user's bot status unless really needed -- skips db query
486 // assumes $botMax >= $max
487 if (!is_null($max) && $value > $max) {
488 if (!is_null($botMax) && ($this->getMain()->isBot() ||
$this->getMain()->isSysop())) {
489 if ($value > $botMax) {
490 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
493 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
499 * Call main module's error handler
501 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
502 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
506 * Internal code errors should be reported with this method
508 protected static function dieDebug($method, $message) {
509 wfDebugDieBacktrace("Internal error in $method: $message");
513 * Profiling: total module execution time
515 private $mTimeIn = 0, $mModuleTime = 0;
518 * Start module profiling
520 public function profileIn() {
521 if ($this->mTimeIn
!== 0)
522 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
523 $this->mTimeIn
= microtime(true);
524 wfProfileIn($this->getModuleProfileName());
528 * End module profiling
530 public function profileOut() {
531 if ($this->mTimeIn
=== 0)
532 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
533 if ($this->mDBTimeIn
!== 0)
534 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
536 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
538 wfProfileOut($this->getModuleProfileName());
542 * When modules crash, sometimes it is needed to do a profileOut() regardless
543 * of the profiling state the module was in. This method does such cleanup.
545 public function safeProfileOut() {
546 if ($this->mTimeIn
!== 0) {
547 if ($this->mDBTimeIn
!== 0)
548 $this->profileDBOut();
554 * Total time the module was executed
556 public function getProfileTime() {
557 if ($this->mTimeIn
!== 0)
558 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
559 return $this->mModuleTime
;
563 * Profiling: database execution time
565 private $mDBTimeIn = 0, $mDBTime = 0;
568 * Start module profiling
570 public function profileDBIn() {
571 if ($this->mTimeIn
=== 0)
572 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
573 if ($this->mDBTimeIn
!== 0)
574 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
575 $this->mDBTimeIn
= microtime(true);
576 wfProfileIn($this->getModuleProfileName(true));
580 * End database profiling
582 public function profileDBOut() {
583 if ($this->mTimeIn
=== 0)
584 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
585 if ($this->mDBTimeIn
=== 0)
586 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
588 $time = microtime(true) - $this->mDBTimeIn
;
589 $this->mDBTimeIn
= 0;
591 $this->mDBTime +
= $time;
592 $this->getMain()->mDBTime +
= $time;
593 wfProfileOut($this->getModuleProfileName(true));
597 * Total time the module used the database
599 public function getProfileDBTime() {
600 if ($this->mDBTimeIn
!== 0)
601 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
602 return $this->mDBTime
;
605 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
606 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
609 print "\n" . wfBacktrace();
613 public abstract function getVersion();
615 public static function getBaseVersion() {
616 return __CLASS__
. ': $Id$';