9e000a05fee83ccee096f9178106a766a47ba553
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 * If the module may only be used with a certain format module,
95 * it should override this method to return an instance of that formatter.
96 * A value of null means the default format will be used.
98 public function getCustomFormatModule() {
103 * Generates help message for this module, or false if there is no description
105 public function makeHelpMsg() {
107 static $lnPrfx = "\n ";
109 $msg = $this->getDescription();
111 if ($msg !== false) {
117 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
120 $paramsMsg = $this->makeHelpMsgParameters();
121 if ($paramsMsg !== false) {
122 $msg .= "Parameters:\n$paramsMsg";
126 $examples = $this->getExamples();
127 if ($examples !== false) {
128 if (!is_array($examples))
132 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
133 $msg .= implode($lnPrfx, $examples) . "\n";
136 if ($this->getMain()->getShowVersions()) {
137 $versions = $this->getVersion();
138 if (is_array($versions))
139 $versions = implode("\n ", $versions);
140 $msg .= "Version:\n $versions\n";
147 public function makeHelpMsgParameters() {
148 $params = $this->getAllowedParams();
149 if ($params !== false) {
151 $paramsDescription = $this->getParamDescription();
153 foreach (array_keys($params) as $paramName) {
154 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
156 $desc = implode("\n" . str_repeat(' ', 19), $desc);
157 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
166 * Returns the description string for this module
168 protected function getDescription() {
173 * Returns usage examples for this module. Return null if no examples are available.
175 protected function getExamples() {
180 * Returns an array of allowed parameters (keys) => default value for that parameter
182 protected function getAllowedParams() {
187 * Returns the description string for the given parameter.
189 protected function getParamDescription() {
194 * This method mangles parameter name based on the prefix supplied to the constructor.
195 * Override this method to change parameter name during runtime
197 public function encodeParamName($paramName) {
198 return $this->mParamPrefix
. $paramName;
202 * Using getAllowedParams(), makes an array of the values provided by the user,
203 * with key being the name of the variable, and value - validated value from user or default.
204 * This method can be used to generate local variables using extract().
206 public function extractRequestParams() {
207 $params = $this->getAllowedParams();
210 foreach ($params as $paramName => $paramSettings)
211 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
217 * Get a value for the given parameter
219 protected function getParameter($paramName) {
220 $params = $this->getAllowedParams();
221 $paramSettings = $params[$paramName];
222 return $this->getParameterFromSettings($paramName, $paramSettings);
226 * Using the settings determine the value for the given parameter
227 * @param $paramName String: parameter name
228 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
230 protected function getParameterFromSettings($paramName, $paramSettings) {
232 // Some classes may decide to change parameter names
233 $paramName = $this->encodeParamName($paramName);
235 if (!is_array($paramSettings)) {
236 $default = $paramSettings;
238 $type = gettype($paramSettings);
240 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
241 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
242 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
244 // When type is not given, and no choices, the type is the same as $default
245 if (!isset ($type)) {
246 if (isset ($default))
247 $type = gettype($default);
249 $type = 'NULL'; // allow everything
253 if ($type == 'boolean') {
254 if (isset ($default) && $default !== false) {
255 // Having a default value of anything other than 'false' is pointless
256 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
259 $value = $this->getMain()->getRequest()->getCheck($paramName);
261 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
264 if (isset ($value) && ($multi ||
is_array($type)))
265 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
267 // More validation only when choices were not given
268 // choices were validated in parseMultiValue()
269 if (!is_array($type) && isset ($value)) {
272 case 'NULL' : // nothing to do
274 case 'string' : // nothing to do
276 case 'integer' : // Force everything using intval()
277 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
280 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
281 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
283 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
284 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
285 $value = intval($value);
286 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
290 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
294 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
295 if (!preg_match('/^[0-9]{14}$/', $value))
296 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$valueName}");
299 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
304 // There should never be any duplicate values in a list
305 if (is_array($value))
306 $value = array_unique($value);
312 * Return an array of values that were given in a 'a|b|c' notation,
313 * after it optionally validates them against the list allowed values.
315 * @param valueName - The name of the parameter (for error reporting)
316 * @param value - The value being parsed
317 * @param allowMultiple - Can $value contain more than one value separated by '|'?
318 * @param allowedValues - An array of values to check against. If null, all values are accepted.
319 * @return (allowMultiple ? an_array_of_values : a_single_value)
321 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
322 $valuesList = explode('|', $value);
323 if (!$allowMultiple && count($valuesList) != 1) {
324 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
325 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
327 if (is_array($allowedValues)) {
328 $unknownValues = array_diff($valuesList, $allowedValues);
329 if ($unknownValues) {
330 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
334 return $allowMultiple ?
$valuesList : $valuesList[0];
338 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
340 function validateLimit($varname, $value, $min, $max, $botMax) {
344 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
347 if ($this->getMain()->isBot()) {
348 if ($value > $botMax) {
349 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
352 elseif ($value > $max) {
353 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
358 * Call main module's error handler
360 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
361 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
365 * Internal code errors should be reported with this method
367 protected static function dieDebug($method, $message) {
368 wfDebugDieBacktrace("Internal error in $method: $message");
372 * Profiling: total module execution time
374 private $mTimeIn = 0, $mModuleTime = 0;
377 * Start module profiling
379 public function profileIn() {
380 if ($this->mTimeIn
!== 0)
381 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
382 $this->mTimeIn
= microtime(true);
386 * End module profiling
388 public function profileOut() {
389 if ($this->mTimeIn
=== 0)
390 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
391 if ($this->mDBTimeIn
!== 0)
392 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
394 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
399 * Total time the module was executed
401 public function getProfileTime() {
402 if ($this->mTimeIn
!== 0)
403 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
404 return $this->mModuleTime
;
408 * Profiling: database execution time
410 private $mDBTimeIn = 0, $mDBTime = 0;
413 * Start module profiling
415 public function profileDBIn() {
416 if ($this->mTimeIn
=== 0)
417 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
418 if ($this->mDBTimeIn
!== 0)
419 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
420 $this->mDBTimeIn
= microtime(true);
424 * End database profiling
426 public function profileDBOut() {
427 if ($this->mTimeIn
=== 0)
428 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
429 if ($this->mDBTimeIn
=== 0)
430 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
432 $time = microtime(true) - $this->mDBTimeIn
;
433 $this->mDBTimeIn
= 0;
435 $this->mDBTime +
= $time;
436 $this->getMain()->mDBTime +
= $time;
440 * Total time the module used the database
442 public function getProfileDBTime() {
443 if ($this->mDBTimeIn
!== 0)
444 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
445 return $this->mDBTime
;
448 public abstract function getVersion();
450 public static function getBaseVersion() {
451 return __CLASS__
. ': $Id$';