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 getCustomPrinter() {
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 $paramPrefix = "\n" . str_repeat(' ', 19);
154 foreach ($params as $paramName => &$paramSettings) {
155 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
157 $desc = implode($paramPrefix, $desc);
158 if (isset ($paramSettings[self
:: PARAM_TYPE
])) {
159 $type = $paramSettings[self
:: PARAM_TYPE
];
160 if (is_array($type)) {
161 $desc .= $paramPrefix . 'Allowed values: '. implode(', ', $type);
165 $default = is_array($paramSettings)
166 ?
(isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null)
168 if (!is_null($default) && $default !== false)
169 $desc .= $paramPrefix . "Default: $default";
171 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
180 * Returns the description string for this module
182 protected function getDescription() {
187 * Returns usage examples for this module. Return null if no examples are available.
189 protected function getExamples() {
194 * Returns an array of allowed parameters (keys) => default value for that parameter
196 protected function getAllowedParams() {
201 * Returns the description string for the given parameter.
203 protected function getParamDescription() {
208 * This method mangles parameter name based on the prefix supplied to the constructor.
209 * Override this method to change parameter name during runtime
211 public function encodeParamName($paramName) {
212 return $this->mParamPrefix
. $paramName;
216 * Using getAllowedParams(), makes an array of the values provided by the user,
217 * with key being the name of the variable, and value - validated value from user or default.
218 * This method can be used to generate local variables using extract().
220 public function extractRequestParams() {
221 $params = $this->getAllowedParams();
224 foreach ($params as $paramName => $paramSettings)
225 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
231 * Get a value for the given parameter
233 protected function getParameter($paramName) {
234 $params = $this->getAllowedParams();
235 $paramSettings = $params[$paramName];
236 return $this->getParameterFromSettings($paramName, $paramSettings);
240 * Using the settings determine the value for the given parameter
241 * @param $paramName String: parameter name
242 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
244 protected function getParameterFromSettings($paramName, $paramSettings) {
246 // Some classes may decide to change parameter names
247 $paramName = $this->encodeParamName($paramName);
249 if (!is_array($paramSettings)) {
250 $default = $paramSettings;
252 $type = gettype($paramSettings);
254 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
255 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
256 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
258 // When type is not given, and no choices, the type is the same as $default
259 if (!isset ($type)) {
260 if (isset ($default))
261 $type = gettype($default);
263 $type = 'NULL'; // allow everything
267 if ($type == 'boolean') {
268 if (isset ($default) && $default !== false) {
269 // Having a default value of anything other than 'false' is pointless
270 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
273 $value = $this->getMain()->getRequest()->getCheck($paramName);
275 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
278 if (isset ($value) && ($multi ||
is_array($type)))
279 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
281 // More validation only when choices were not given
282 // choices were validated in parseMultiValue()
283 if (!is_array($type) && isset ($value)) {
286 case 'NULL' : // nothing to do
288 case 'string' : // nothing to do
290 case 'integer' : // Force everything using intval()
291 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
294 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
295 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
297 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
298 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
299 $value = intval($value);
300 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
304 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
308 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
309 if (!preg_match('/^[0-9]{14}$/', $value))
310 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$valueName}");
313 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
318 // There should never be any duplicate values in a list
319 if (is_array($value))
320 $value = array_unique($value);
326 * Return an array of values that were given in a 'a|b|c' notation,
327 * after it optionally validates them against the list allowed values.
329 * @param valueName - The name of the parameter (for error reporting)
330 * @param value - The value being parsed
331 * @param allowMultiple - Can $value contain more than one value separated by '|'?
332 * @param allowedValues - An array of values to check against. If null, all values are accepted.
333 * @return (allowMultiple ? an_array_of_values : a_single_value)
335 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
336 $valuesList = explode('|', $value);
337 if (!$allowMultiple && count($valuesList) != 1) {
338 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
339 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
341 if (is_array($allowedValues)) {
342 $unknownValues = array_diff($valuesList, $allowedValues);
343 if ($unknownValues) {
344 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
348 return $allowMultiple ?
$valuesList : $valuesList[0];
352 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
354 function validateLimit($varname, $value, $min, $max, $botMax) {
358 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
361 if ($this->getMain()->isBot()) {
362 if ($value > $botMax) {
363 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
366 elseif ($value > $max) {
367 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
372 * Call main module's error handler
374 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
375 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
379 * Internal code errors should be reported with this method
381 protected static function dieDebug($method, $message) {
382 wfDebugDieBacktrace("Internal error in $method: $message");
386 * Profiling: total module execution time
388 private $mTimeIn = 0, $mModuleTime = 0;
391 * Start module profiling
393 public function profileIn() {
394 if ($this->mTimeIn
!== 0)
395 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
396 $this->mTimeIn
= microtime(true);
400 * End module profiling
402 public function profileOut() {
403 if ($this->mTimeIn
=== 0)
404 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
405 if ($this->mDBTimeIn
!== 0)
406 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
408 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
413 * Total time the module was executed
415 public function getProfileTime() {
416 if ($this->mTimeIn
!== 0)
417 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
418 return $this->mModuleTime
;
422 * Profiling: database execution time
424 private $mDBTimeIn = 0, $mDBTime = 0;
427 * Start module profiling
429 public function profileDBIn() {
430 if ($this->mTimeIn
=== 0)
431 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
432 if ($this->mDBTimeIn
!== 0)
433 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
434 $this->mDBTimeIn
= microtime(true);
438 * End database profiling
440 public function profileDBOut() {
441 if ($this->mTimeIn
=== 0)
442 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
443 if ($this->mDBTimeIn
=== 0)
444 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
446 $time = microtime(true) - $this->mDBTimeIn
;
447 $this->mDBTimeIn
= 0;
449 $this->mDBTime +
= $time;
450 $this->getMain()->mDBTime +
= $time;
454 * Total time the module used the database
456 public function getProfileDBTime() {
457 if ($this->mDBTimeIn
!== 0)
458 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
459 return $this->mDBTime
;
462 public abstract function getVersion();
464 public static function getBaseVersion() {
465 return __CLASS__
. ': $Id$';