4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@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 * @todo Document - e.g. Provide top-level description of this class.
30 abstract class ApiBase
{
32 // These constants allow modules to specify exactly how to treat incomming parameters.
35 const PARAM_ISMULTI
= 1;
41 const LIMIT_BIG1
= 500; // Fast query, user's limit
42 const LIMIT_BIG2
= 5000; // Fast query, bot's limit
43 const LIMIT_SML1
= 50; // Slow query, user's limit
44 const LIMIT_SML2
= 500; // Slow query, bot's limit
46 private $mMainModule, $mModuleName, $mParamPrefix;
51 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
52 $this->mMainModule
= $mainModule;
53 $this->mModuleName
= $moduleName;
54 $this->mParamPrefix
= $paramPrefix;
58 * Executes this module
60 public abstract function execute();
63 * Get the name of the module being executed by this instance
65 public function getModuleName() {
66 return $this->mModuleName
;
70 * Get the name of the module as shown in the profiler log
72 public function getModuleProfileName($db = false) {
74 return 'API:' . $this->mModuleName
. '-DB';
76 return 'API:' . $this->mModuleName
;
82 public function getMain() {
83 return $this->mMainModule
;
87 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
89 public function isMain() {
90 return $this === $this->mMainModule
;
96 public function getResult() {
97 // Main module has getResult() method overriden
98 // Safety - avoid infinite loop:
100 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
101 return $this->getMain()->getResult();
105 * Get the result data array
107 public function & getResultData() {
108 return $this->getResult()->getData();
112 * If the module may only be used with a certain format module,
113 * it should override this method to return an instance of that formatter.
114 * A value of null means the default format will be used.
116 public function getCustomPrinter() {
121 * Generates help message for this module, or false if there is no description
123 public function makeHelpMsg() {
125 static $lnPrfx = "\n ";
127 $msg = $this->getDescription();
129 if ($msg !== false) {
135 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
138 $paramsMsg = $this->makeHelpMsgParameters();
139 if ($paramsMsg !== false) {
140 $msg .= "Parameters:\n$paramsMsg";
144 $examples = $this->getExamples();
145 if ($examples !== false) {
146 if (!is_array($examples))
150 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
151 $msg .= implode($lnPrfx, $examples) . "\n";
154 if ($this->getMain()->getShowVersions()) {
155 $versions = $this->getVersion();
156 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
157 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
159 if (is_array($versions)) {
160 foreach ($versions as &$v)
161 $v = eregi_replace($pattern, $replacement, $v);
162 $versions = implode("\n ", $versions);
165 $versions = eregi_replace($pattern, $replacement, $versions);
167 $msg .= "Version:\n $versions\n";
174 public function makeHelpMsgParameters() {
175 $params = $this->getAllowedParams();
176 if ($params !== false) {
178 $paramsDescription = $this->getParamDescription();
180 $paramPrefix = "\n" . str_repeat(' ', 19);
181 foreach ($params as $paramName => $paramSettings) {
182 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
184 $desc = implode($paramPrefix, $desc);
186 @ $type = $paramSettings[self
:: PARAM_TYPE
];
188 if (isset ($paramSettings[self
:: PARAM_ISMULTI
]))
189 $prompt = 'Values (separate with \'|\'): ';
191 $prompt = 'One value: ';
193 if (is_array($type)) {
194 $desc .= $paramPrefix . $prompt . implode(', ', $type);
196 elseif ($type == 'namespace') {
197 // Special handling because namespaces are type-limited, yet they are not given
198 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase
:: getValidNamespaces());
202 $default = is_array($paramSettings) ?
(isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null) : $paramSettings;
203 if (!is_null($default) && $default !== false)
204 $desc .= $paramPrefix . "Default: $default";
206 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
215 * Returns the description string for this module
217 protected function getDescription() {
222 * Returns usage examples for this module. Return null if no examples are available.
224 protected function getExamples() {
229 * Returns an array of allowed parameters (keys) => default value for that parameter
231 protected function getAllowedParams() {
236 * Returns the description string for the given parameter.
238 protected function getParamDescription() {
243 * This method mangles parameter name based on the prefix supplied to the constructor.
244 * Override this method to change parameter name during runtime
246 public function encodeParamName($paramName) {
247 return $this->mParamPrefix
. $paramName;
251 * Using getAllowedParams(), makes an array of the values provided by the user,
252 * with key being the name of the variable, and value - validated value from user or default.
253 * This method can be used to generate local variables using extract().
255 public function extractRequestParams() {
256 $params = $this->getAllowedParams();
259 foreach ($params as $paramName => $paramSettings)
260 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
266 * Get a value for the given parameter
268 protected function getParameter($paramName) {
269 $params = $this->getAllowedParams();
270 $paramSettings = $params[$paramName];
271 return $this->getParameterFromSettings($paramName, $paramSettings);
274 public static function getValidNamespaces() {
275 static $mValidNamespaces = null;
276 if (is_null($mValidNamespaces)) {
279 $mValidNamespaces = array ();
280 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
282 $mValidNamespaces[] = $ns;
285 return $mValidNamespaces;
289 * Using the settings determine the value for the given parameter
290 * @param $paramName String: parameter name
291 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
293 protected function getParameterFromSettings($paramName, $paramSettings) {
295 // Some classes may decide to change parameter names
296 $paramName = $this->encodeParamName($paramName);
298 if (!is_array($paramSettings)) {
299 $default = $paramSettings;
301 $type = gettype($paramSettings);
303 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
304 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
305 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
307 // When type is not given, and no choices, the type is the same as $default
308 if (!isset ($type)) {
309 if (isset ($default))
310 $type = gettype($default);
312 $type = 'NULL'; // allow everything
316 if ($type == 'boolean') {
317 if (isset ($default) && $default !== false) {
318 // Having a default value of anything other than 'false' is pointless
319 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
322 $value = $this->getMain()->getRequest()->getCheck($paramName);
324 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
326 if (isset ($value) && $type == 'namespace')
327 $type = ApiBase
:: getValidNamespaces();
330 if (isset ($value) && ($multi ||
is_array($type)))
331 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
333 // More validation only when choices were not given
334 // choices were validated in parseMultiValue()
335 if (isset ($value)) {
336 if (!is_array($type)) {
338 case 'NULL' : // nothing to do
340 case 'string' : // nothing to do
342 case 'integer' : // Force everything using intval()
343 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
346 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
347 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
349 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
350 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
351 $value = intval($value);
352 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
356 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
360 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
361 $value = wfTimestamp(TS_UNIX
, $value);
363 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
364 $value = wfTimestamp(TS_MW
, $value);
367 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
371 // There should never be any duplicate values in a list
372 if (is_array($value))
373 $value = array_unique($value);
380 * Return an array of values that were given in a 'a|b|c' notation,
381 * after it optionally validates them against the list allowed values.
383 * @param valueName - The name of the parameter (for error reporting)
384 * @param value - The value being parsed
385 * @param allowMultiple - Can $value contain more than one value separated by '|'?
386 * @param allowedValues - An array of values to check against. If null, all values are accepted.
387 * @return (allowMultiple ? an_array_of_values : a_single_value)
389 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
390 $valuesList = explode('|', $value);
391 if (!$allowMultiple && count($valuesList) != 1) {
392 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
393 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
395 if (is_array($allowedValues)) {
396 $unknownValues = array_diff($valuesList, $allowedValues);
397 if ($unknownValues) {
398 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s" : "") . " for parameter '$valueName'", "unknown_$valueName");
402 return $allowMultiple ?
$valuesList : $valuesList[0];
406 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
408 function validateLimit($varname, $value, $min, $max, $botMax) {
410 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
413 if ($this->getMain()->isBot()) {
414 if ($value > $botMax) {
415 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
418 elseif ($value > $max) {
419 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
424 * Call main module's error handler
426 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
427 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
431 * Internal code errors should be reported with this method
433 protected static function dieDebug($method, $message) {
434 wfDebugDieBacktrace("Internal error in $method: $message");
438 * Profiling: total module execution time
440 private $mTimeIn = 0, $mModuleTime = 0;
443 * Start module profiling
445 public function profileIn() {
446 if ($this->mTimeIn
!== 0)
447 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
448 $this->mTimeIn
= microtime(true);
449 wfProfileIn($this->getModuleProfileName());
453 * End module profiling
455 public function profileOut() {
456 if ($this->mTimeIn
=== 0)
457 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
458 if ($this->mDBTimeIn
!== 0)
459 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
461 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
463 wfProfileOut($this->getModuleProfileName());
467 * When modules crash, sometimes it is needed to do a profileOut() regardless
468 * of the profiling state the module was in. This method does such cleanup.
470 public function safeProfileOut() {
471 if ($this->mTimeIn
!== 0) {
472 if ($this->mDBTimeIn
!== 0)
473 $this->profileDBOut();
479 * Total time the module was executed
481 public function getProfileTime() {
482 if ($this->mTimeIn
!== 0)
483 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
484 return $this->mModuleTime
;
488 * Profiling: database execution time
490 private $mDBTimeIn = 0, $mDBTime = 0;
493 * Start module profiling
495 public function profileDBIn() {
496 if ($this->mTimeIn
=== 0)
497 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
498 if ($this->mDBTimeIn
!== 0)
499 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
500 $this->mDBTimeIn
= microtime(true);
501 wfProfileIn($this->getModuleProfileName(true));
505 * End database profiling
507 public function profileDBOut() {
508 if ($this->mTimeIn
=== 0)
509 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
510 if ($this->mDBTimeIn
=== 0)
511 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
513 $time = microtime(true) - $this->mDBTimeIn
;
514 $this->mDBTimeIn
= 0;
516 $this->mDBTime +
= $time;
517 $this->getMain()->mDBTime +
= $time;
518 wfProfileOut($this->getModuleProfileName(true));
522 * Total time the module used the database
524 public function getProfileDBTime() {
525 if ($this->mDBTimeIn
!== 0)
526 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
527 return $this->mDBTime
;
530 public abstract function getVersion();
532 public static function getBaseVersion() {
533 return __CLASS__
. ': $Id$';