5 * Created on Sep 5, 2006
7 * API for MediaWiki 1.8+
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
27 abstract class ApiBase
{
29 // These constants allow modules to specify exactly how to treat incomming parameters.
32 const PARAM_ISMULTI
= 1;
43 public function __construct($mainModule) {
44 $this->mMainModule
= $mainModule;
48 * Executes this module
50 public abstract function execute();
55 public function getMain() {
56 return $this->mMainModule
;
60 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
62 public function isMain() {
63 return $this === $this->mMainModule
;
69 public function getResult() {
70 // Main module has getResult() method overriden
71 // Safety - avoid infinite loop:
73 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
74 return $this->getMain()->getResult();
78 * Get the result data array
80 public function & getResultData() {
81 return $this->getResult()->getData();
85 * Generates help message for this module, or false if there is no description
87 public function makeHelpMsg() {
89 static $lnPrfx = "\n ";
91 $msg = $this->getDescription();
99 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
102 $paramsMsg = $this->makeHelpMsgParameters();
103 if ($paramsMsg !== false) {
104 $msg .= "Parameters:\n$paramsMsg";
108 $examples = $this->getExamples();
109 if ($examples !== false) {
110 if (!is_array($examples))
114 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
115 $msg .= implode($lnPrfx, $examples) . "\n";
118 if ($this->getMain()->getShowVersions()) {
119 $versions = $this->getVersion();
120 if (is_array($versions))
121 $versions = implode("\n ", $versions);
122 $msg .= "Version:\n $versions\n";
129 public function makeHelpMsgParameters() {
130 $params = $this->getAllowedParams();
131 if ($params !== false) {
133 $paramsDescription = $this->getParamDescription();
135 foreach (array_keys($params) as $paramName) {
136 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
138 $desc = implode("\n" . str_repeat(' ', 19), $desc);
139 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
148 * Returns the description string for this module
150 protected function getDescription() {
155 * Returns usage examples for this module. Return null if no examples are available.
157 protected function getExamples() {
162 * Returns an array of allowed parameters (keys) => default value for that parameter
164 protected function getAllowedParams() {
169 * Returns the description string for the given parameter.
171 protected function getParamDescription() {
176 * Using getAllowedParams(), makes an array of the values provided by the user,
177 * with key being the name of the variable, and value - validated value from user or default.
178 * This method can be used to generate local variables using extract().
180 public function extractRequestParams() {
181 $params = $this->getAllowedParams();
184 foreach ($params as $paramName => $paramSettings)
185 $results[$paramName] = $this->getParameter($paramName, $paramSettings);
190 public function getParameter($paramName, $paramSettings) {
193 if (!is_array($paramSettings)) {
194 $default = $paramSettings;
196 $type = gettype($paramSettings);
198 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
199 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
200 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
202 // When type is not given, and no choices, the type is the same as $default
203 if (!isset ($type)) {
204 if (isset ($default))
205 $type = gettype($default);
207 $type = 'NULL'; // allow everything
211 if ($type == 'boolean') {
212 if (isset ($default) && $default !== false) {
213 // Having a default value of anything other than 'false' is pointless
214 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
217 $value = $wgRequest->getCheck($paramName);
219 $value = $wgRequest->getVal($paramName, $default);
221 if (isset ($value) && ($multi ||
is_array($type)))
222 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
224 // More validation only when choices were not given
225 // choices were validated in parseMultiValue()
226 if (!is_array($type) && isset ($value)) {
229 case 'NULL' : // nothing to do
231 case 'string' : // nothing to do
233 case 'integer' : // Force everything using intval()
234 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
237 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
238 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
240 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
241 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
242 $value = intval($value);
243 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
247 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
251 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
252 if (!preg_match('/^[0-9]{14}$/', $value))
253 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$valueName}");
256 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
265 * Return an array of values that were given in a 'a|b|c' notation,
266 * after it optionally validates them against the list allowed values.
268 * @param valueName - The name of the parameter (for error reporting)
269 * @param value - The value being parsed
270 * @param allowMultiple - Can $value contain more than one value separated by '|'?
271 * @param allowedValues - An array of values to check against. If null, all values are accepted.
272 * @return (allowMultiple ? an_array_of_values : a_single_value)
274 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
275 $valuesList = explode('|', $value);
276 if (!$allowMultiple && count($valuesList) != 1) {
277 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
278 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
280 if (is_array($allowedValues)) {
281 $unknownValues = array_diff($valuesList, $allowedValues);
282 if ($unknownValues) {
283 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
287 return $allowMultiple ?
$valuesList : $valuesList[0];
291 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
293 function validateLimit($varname, $value, $min, $max, $botMax) {
297 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
300 if ($this->getMain()->isBot()) {
301 if ($value > $botMax) {
302 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
305 elseif ($value > $max) {
306 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
311 * Call main module's error handler
313 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
314 $this->getMain()->mainDieUsage($description, $errorCode, $httpRespCode);
318 * Internal code errors should be reported with this method
320 protected static function dieDebug($method, $message) {
321 wfDebugDieBacktrace("Internal error in $method: $message");
325 * Profiling: total module execution time
327 private $mTimeIn = 0, $mModuleTime = 0;
330 * Start module profiling
332 public function profileIn() {
333 if ($this->mTimeIn
!== 0)
334 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
335 $this->mTimeIn
= microtime(true);
339 * End module profiling
341 public function profileOut() {
342 if ($this->mTimeIn
=== 0)
343 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
344 if ($this->mDBTimeIn
!== 0)
345 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
347 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
352 * Total time the module was executed
354 public function getProfileTime() {
355 if ($this->mTimeIn
!== 0)
356 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
357 return $this->mModuleTime
;
361 * Profiling: database execution time
363 private $mDBTimeIn = 0, $mDBTime = 0;
366 * Start module profiling
368 public function profileDBIn() {
369 if ($this->mTimeIn
=== 0)
370 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
371 if ($this->mDBTimeIn
!== 0)
372 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
373 $this->mDBTimeIn
= microtime(true);
377 * End database profiling
379 public function profileDBOut() {
380 if ($this->mTimeIn
=== 0)
381 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
382 if ($this->mDBTimeIn
=== 0)
383 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
385 $time = microtime(true) - $this->mDBTimeIn
;
386 $this->mDBTimeIn
= 0;
388 $this->mDBTime +
= $time;
389 $this->getMain()->mDBTime +
= $time;
393 * Total time the module used the database
395 public function getProfileDBTime() {
396 if ($this->mDBTimeIn
!== 0)
397 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
398 return $this->mDBTime
;
401 public function getVersion() {
402 return __CLASS__
. ': $Id$';