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, user's limit
51 const LIMIT_BIG2
= 5000; // Fast query, bot's limit
52 const LIMIT_SML1
= 50; // Slow query, user's limit
53 const LIMIT_SML2
= 500; // Slow query, bot's limit
55 private $mMainModule, $mModuleName, $mParamPrefix;
60 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
61 $this->mMainModule
= $mainModule;
62 $this->mModuleName
= $moduleName;
63 $this->mParamPrefix
= $paramPrefix;
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 the name of the module as shown in the profiler log
81 public function getModuleProfileName($db = false) {
83 return 'API:' . $this->mModuleName
. '-DB';
85 return 'API:' . $this->mModuleName
;
91 public function getMain() {
92 return $this->mMainModule
;
96 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
98 public function isMain() {
99 return $this === $this->mMainModule
;
105 public function getResult() {
106 // Main module has getResult() method overriden
107 // Safety - avoid infinite loop:
109 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
110 return $this->getMain()->getResult();
114 * Get the result data array
116 public function & getResultData() {
117 return $this->getResult()->getData();
121 * If the module may only be used with a certain format module,
122 * it should override this method to return an instance of that formatter.
123 * A value of null means the default format will be used.
125 public function getCustomPrinter() {
130 * Generates help message for this module, or false if there is no description
132 public function makeHelpMsg() {
134 static $lnPrfx = "\n ";
136 $msg = $this->getDescription();
138 if ($msg !== false) {
144 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
147 $paramsMsg = $this->makeHelpMsgParameters();
148 if ($paramsMsg !== false) {
149 $msg .= "Parameters:\n$paramsMsg";
153 $examples = $this->getExamples();
154 if ($examples !== false) {
155 if (!is_array($examples))
159 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
160 $msg .= implode($lnPrfx, $examples) . "\n";
163 if ($this->getMain()->getShowVersions()) {
164 $versions = $this->getVersion();
165 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
166 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
168 if (is_array($versions)) {
169 foreach ($versions as &$v)
170 $v = eregi_replace($pattern, $replacement, $v);
171 $versions = implode("\n ", $versions);
174 $versions = eregi_replace($pattern, $replacement, $versions);
176 $msg .= "Version:\n $versions\n";
183 public function makeHelpMsgParameters() {
184 $params = $this->getAllowedParams();
185 if ($params !== false) {
187 $paramsDescription = $this->getParamDescription();
189 $paramPrefix = "\n" . str_repeat(' ', 19);
190 foreach ($params as $paramName => $paramSettings) {
191 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
193 $desc = implode($paramPrefix, $desc);
195 @ $type = $paramSettings[self
:: PARAM_TYPE
];
197 if (isset ($paramSettings[self
:: PARAM_ISMULTI
]))
198 $prompt = 'Values (separate with \'|\'): ';
200 $prompt = 'One value: ';
202 if (is_array($type)) {
204 $nothingPrompt = false;
205 foreach ($type as $t)
207 $nothingPrompt = 'Can be empty, or ';
210 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
214 // Special handling because namespaces are type-limited, yet they are not given
215 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase
:: getValidNamespaces());
218 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
221 $hasMin = isset($paramSettings[self
:: PARAM_MIN
]);
222 $hasMax = isset($paramSettings[self
:: PARAM_MAX
]);
223 if ($hasMin ||
$hasMax) {
225 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
227 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
229 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
231 $desc .= $paramPrefix . $intRangeStr;
238 $default = is_array($paramSettings) ?
(isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null) : $paramSettings;
239 if (!is_null($default) && $default !== false)
240 $desc .= $paramPrefix . "Default: $default";
242 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
251 * Returns the description string for this module
253 protected function getDescription() {
258 * Returns usage examples for this module. Return null if no examples are available.
260 protected function getExamples() {
265 * Returns an array of allowed parameters (keys) => default value for that parameter
267 protected function getAllowedParams() {
272 * Returns the description string for the given parameter.
274 protected function getParamDescription() {
279 * This method mangles parameter name based on the prefix supplied to the constructor.
280 * Override this method to change parameter name during runtime
282 public function encodeParamName($paramName) {
283 return $this->mParamPrefix
. $paramName;
287 * Using getAllowedParams(), makes an array of the values provided by the user,
288 * with key being the name of the variable, and value - validated value from user or default.
289 * This method can be used to generate local variables using extract().
291 public function extractRequestParams() {
292 $params = $this->getAllowedParams();
295 foreach ($params as $paramName => $paramSettings)
296 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
302 * Get a value for the given parameter
304 protected function getParameter($paramName) {
305 $params = $this->getAllowedParams();
306 $paramSettings = $params[$paramName];
307 return $this->getParameterFromSettings($paramName, $paramSettings);
310 public static function getValidNamespaces() {
311 static $mValidNamespaces = null;
312 if (is_null($mValidNamespaces)) {
315 $mValidNamespaces = array ();
316 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
318 $mValidNamespaces[] = $ns;
321 return $mValidNamespaces;
325 * Using the settings determine the value for the given parameter
326 * @param $paramName String: parameter name
327 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
329 protected function getParameterFromSettings($paramName, $paramSettings) {
331 // Some classes may decide to change parameter names
332 $paramName = $this->encodeParamName($paramName);
334 if (!is_array($paramSettings)) {
335 $default = $paramSettings;
337 $type = gettype($paramSettings);
339 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
340 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
341 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
343 // When type is not given, and no choices, the type is the same as $default
344 if (!isset ($type)) {
345 if (isset ($default))
346 $type = gettype($default);
348 $type = 'NULL'; // allow everything
352 if ($type == 'boolean') {
353 if (isset ($default) && $default !== false) {
354 // Having a default value of anything other than 'false' is pointless
355 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
358 $value = $this->getMain()->getRequest()->getCheck($paramName);
360 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
362 if (isset ($value) && $type == 'namespace')
363 $type = ApiBase
:: getValidNamespaces();
366 if (isset ($value) && ($multi ||
is_array($type)))
367 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
369 // More validation only when choices were not given
370 // choices were validated in parseMultiValue()
371 if (isset ($value)) {
372 if (!is_array($type)) {
374 case 'NULL' : // nothing to do
376 case 'string' : // nothing to do
378 case 'integer' : // Force everything using intval() and optionally validate limits
380 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
381 $checkMin = isset ($paramSettings[self
:: PARAM_MIN
]);
382 $checkMax = isset ($paramSettings[self
:: PARAM_MAX
]);
384 if ($checkMin ||
$checkMax) {
385 $min = $checkMin ?
$paramSettings[self
:: PARAM_MIN
] : false;
386 $max = $checkMax ?
$paramSettings[self
:: PARAM_MAX
] : false;
388 $values = is_array($value) ?
$value : array($value);
389 foreach ($values as $v) {
390 if ($checkMin && $v < $min)
391 $this->dieUsage("$paramName may not be less than $min (set to $v)", $paramName);
392 if ($checkMax && $v > $max)
393 $this->dieUsage("$paramName may not be over $max (set to $v)", $paramName);
398 if (!isset ($paramSettings[self
:: PARAM_MAX
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
399 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
401 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
402 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
403 $value = intval($value);
404 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX
], $paramSettings[self
:: PARAM_MAX2
]);
408 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
412 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
413 $value = wfTimestamp(TS_UNIX
, $value);
415 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
416 $value = wfTimestamp(TS_MW
, $value);
419 $title = Title
::makeTitleSafe( NS_USER
, $value );
420 if ( is_null( $title ) )
421 $this->dieUsage("Invalid value $user for user parameter $paramName", "baduser_{$paramName}");
422 $value = $title->getText();
425 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
429 // There should never be any duplicate values in a list
430 if (is_array($value))
431 $value = array_unique($value);
438 * Return an array of values that were given in a 'a|b|c' notation,
439 * after it optionally validates them against the list allowed values.
441 * @param valueName - The name of the parameter (for error reporting)
442 * @param value - The value being parsed
443 * @param allowMultiple - Can $value contain more than one value separated by '|'?
444 * @param allowedValues - An array of values to check against. If null, all values are accepted.
445 * @return (allowMultiple ? an_array_of_values : a_single_value)
447 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
448 $valuesList = explode('|', $value);
449 if (!$allowMultiple && count($valuesList) != 1) {
450 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
451 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
453 if (is_array($allowedValues)) {
454 $unknownValues = array_diff($valuesList, $allowedValues);
455 if ($unknownValues) {
456 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s" : "") . " for parameter '$valueName'", "unknown_$valueName");
460 return $allowMultiple ?
$valuesList : $valuesList[0];
464 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
466 function validateLimit($varname, $value, $min, $max, $botMax) {
468 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
471 if ($this->getMain()->isBot()) {
472 if ($value > $botMax) {
473 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
476 elseif ($value > $max) {
477 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
482 * Call main module's error handler
484 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
485 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
489 * Internal code errors should be reported with this method
491 protected static function dieDebug($method, $message) {
492 wfDebugDieBacktrace("Internal error in $method: $message");
496 * Profiling: total module execution time
498 private $mTimeIn = 0, $mModuleTime = 0;
501 * Start module profiling
503 public function profileIn() {
504 if ($this->mTimeIn
!== 0)
505 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
506 $this->mTimeIn
= microtime(true);
507 wfProfileIn($this->getModuleProfileName());
511 * End module profiling
513 public function profileOut() {
514 if ($this->mTimeIn
=== 0)
515 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
516 if ($this->mDBTimeIn
!== 0)
517 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
519 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
521 wfProfileOut($this->getModuleProfileName());
525 * When modules crash, sometimes it is needed to do a profileOut() regardless
526 * of the profiling state the module was in. This method does such cleanup.
528 public function safeProfileOut() {
529 if ($this->mTimeIn
!== 0) {
530 if ($this->mDBTimeIn
!== 0)
531 $this->profileDBOut();
537 * Total time the module was executed
539 public function getProfileTime() {
540 if ($this->mTimeIn
!== 0)
541 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
542 return $this->mModuleTime
;
546 * Profiling: database execution time
548 private $mDBTimeIn = 0, $mDBTime = 0;
551 * Start module profiling
553 public function profileDBIn() {
554 if ($this->mTimeIn
=== 0)
555 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
556 if ($this->mDBTimeIn
!== 0)
557 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
558 $this->mDBTimeIn
= microtime(true);
559 wfProfileIn($this->getModuleProfileName(true));
563 * End database profiling
565 public function profileDBOut() {
566 if ($this->mTimeIn
=== 0)
567 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
568 if ($this->mDBTimeIn
=== 0)
569 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
571 $time = microtime(true) - $this->mDBTimeIn
;
572 $this->mDBTimeIn
= 0;
574 $this->mDBTime +
= $time;
575 $this->getMain()->mDBTime +
= $time;
576 wfProfileOut($this->getModuleProfileName(true));
580 * Total time the module used the database
582 public function getProfileDBTime() {
583 if ($this->mDBTimeIn
!== 0)
584 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
585 return $this->mDBTime
;
588 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
589 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
592 print "\n" . wfBacktrace();
596 public abstract function getVersion();
598 public static function getBaseVersion() {
599 return __CLASS__
. ': $Id$';