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;
38 private $mMainModule, $mModuleName, $mParamPrefix;
43 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
44 $this->mMainModule
= $mainModule;
45 $this->mModuleName
= $moduleName;
46 $this->mParamPrefix
= $paramPrefix;
50 * Executes this module
52 public abstract function execute();
55 * Get the name of the query being executed by this instance
57 public function getModuleName() {
58 return $this->mModuleName
;
64 public function getMain() {
65 return $this->mMainModule
;
69 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
71 public function isMain() {
72 return $this === $this->mMainModule
;
78 public function getResult() {
79 // Main module has getResult() method overriden
80 // Safety - avoid infinite loop:
82 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
83 return $this->getMain()->getResult();
87 * Get the result data array
89 public function & getResultData() {
90 return $this->getResult()->getData();
94 * Generates help message for this module, or false if there is no description
96 public function makeHelpMsg() {
98 static $lnPrfx = "\n ";
100 $msg = $this->getDescription();
102 if ($msg !== false) {
108 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
111 $paramsMsg = $this->makeHelpMsgParameters();
112 if ($paramsMsg !== false) {
113 $msg .= "Parameters:\n$paramsMsg";
117 $examples = $this->getExamples();
118 if ($examples !== false) {
119 if (!is_array($examples))
123 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
124 $msg .= implode($lnPrfx, $examples) . "\n";
127 if ($this->getMain()->getShowVersions()) {
128 $versions = $this->getVersion();
129 if (is_array($versions))
130 $versions = implode("\n ", $versions);
131 $msg .= "Version:\n $versions\n";
138 public function makeHelpMsgParameters() {
139 $params = $this->getAllowedParams();
140 if ($params !== false) {
142 $paramsDescription = $this->getParamDescription();
144 foreach (array_keys($params) as $paramName) {
145 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
147 $desc = implode("\n" . str_repeat(' ', 19), $desc);
148 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
157 * Returns the description string for this module
159 protected function getDescription() {
164 * Returns usage examples for this module. Return null if no examples are available.
166 protected function getExamples() {
171 * Returns an array of allowed parameters (keys) => default value for that parameter
173 protected function getAllowedParams() {
178 * Returns the description string for the given parameter.
180 protected function getParamDescription() {
185 * This method mangles parameter name based on the prefix supplied to the constructor.
186 * Override this method to change parameter name during runtime
188 public function encodeParamName($paramName) {
189 return $this->mParamPrefix
. $paramName;
193 * Using getAllowedParams(), makes an array of the values provided by the user,
194 * with key being the name of the variable, and value - validated value from user or default.
195 * This method can be used to generate local variables using extract().
197 public function extractRequestParams() {
198 $params = $this->getAllowedParams();
201 foreach ($params as $paramName => $paramSettings)
202 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
208 * Get a value for the given parameter
210 protected function getParameter($paramName) {
211 $params = $this->getAllowedParams();
212 $paramSettings = $params[$paramName];
213 return $this->getParameterFromSettings($paramName, $paramSettings);
217 * Using the settings determine the value for the given parameter
218 * @param $paramName String: parameter name
219 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
221 protected function getParameterFromSettings($paramName, $paramSettings) {
223 // Some classes may decide to change parameter names
224 $paramName = $this->encodeParamName($paramName);
226 if (!is_array($paramSettings)) {
227 $default = $paramSettings;
229 $type = gettype($paramSettings);
231 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
232 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
233 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
235 // When type is not given, and no choices, the type is the same as $default
236 if (!isset ($type)) {
237 if (isset ($default))
238 $type = gettype($default);
240 $type = 'NULL'; // allow everything
244 if ($type == 'boolean') {
245 if (isset ($default) && $default !== false) {
246 // Having a default value of anything other than 'false' is pointless
247 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
250 $value = $this->getMain()->getRequest()->getCheck($paramName);
252 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
255 if (isset ($value) && ($multi ||
is_array($type)))
256 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
258 // More validation only when choices were not given
259 // choices were validated in parseMultiValue()
260 if (!is_array($type) && isset ($value)) {
263 case 'NULL' : // nothing to do
265 case 'string' : // nothing to do
267 case 'integer' : // Force everything using intval()
268 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
271 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
272 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
274 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
275 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
276 $value = intval($value);
277 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
281 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
285 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
286 if (!preg_match('/^[0-9]{14}$/', $value))
287 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$valueName}");
290 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
295 // There should never be any duplicate values in a list
296 if (is_array($value))
297 $value = array_unique($value);
303 * Return an array of values that were given in a 'a|b|c' notation,
304 * after it optionally validates them against the list allowed values.
306 * @param valueName - The name of the parameter (for error reporting)
307 * @param value - The value being parsed
308 * @param allowMultiple - Can $value contain more than one value separated by '|'?
309 * @param allowedValues - An array of values to check against. If null, all values are accepted.
310 * @return (allowMultiple ? an_array_of_values : a_single_value)
312 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
313 $valuesList = explode('|', $value);
314 if (!$allowMultiple && count($valuesList) != 1) {
315 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
316 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
318 if (is_array($allowedValues)) {
319 $unknownValues = array_diff($valuesList, $allowedValues);
320 if ($unknownValues) {
321 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
325 return $allowMultiple ?
$valuesList : $valuesList[0];
329 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
331 function validateLimit($varname, $value, $min, $max, $botMax) {
335 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
338 if ($this->getMain()->isBot()) {
339 if ($value > $botMax) {
340 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
343 elseif ($value > $max) {
344 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
349 * Call main module's error handler
351 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
352 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
356 * Internal code errors should be reported with this method
358 protected static function dieDebug($method, $message) {
359 wfDebugDieBacktrace("Internal error in $method: $message");
363 * Profiling: total module execution time
365 private $mTimeIn = 0, $mModuleTime = 0;
368 * Start module profiling
370 public function profileIn() {
371 if ($this->mTimeIn
!== 0)
372 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
373 $this->mTimeIn
= microtime(true);
377 * End module profiling
379 public function profileOut() {
380 if ($this->mTimeIn
=== 0)
381 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
382 if ($this->mDBTimeIn
!== 0)
383 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
385 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
390 * Total time the module was executed
392 public function getProfileTime() {
393 if ($this->mTimeIn
!== 0)
394 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
395 return $this->mModuleTime
;
399 * Profiling: database execution time
401 private $mDBTimeIn = 0, $mDBTime = 0;
404 * Start module profiling
406 public function profileDBIn() {
407 if ($this->mTimeIn
=== 0)
408 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
409 if ($this->mDBTimeIn
!== 0)
410 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
411 $this->mDBTimeIn
= microtime(true);
415 * End database profiling
417 public function profileDBOut() {
418 if ($this->mTimeIn
=== 0)
419 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
420 if ($this->mDBTimeIn
=== 0)
421 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
423 $time = microtime(true) - $this->mDBTimeIn
;
424 $this->mDBTimeIn
= 0;
426 $this->mDBTime +
= $time;
427 $this->getMain()->mDBTime +
= $time;
431 * Total time the module used the database
433 public function getProfileDBTime() {
434 if ($this->mDBTimeIn
!== 0)
435 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
436 return $this->mDBTime
;
439 public abstract function getVersion();
441 public static function getBaseVersion() {
442 return __CLASS__
. ': $Id$';