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 // Multi-valued enums, limit the values user can supply for the parameter
28 define('GN_ENUM_DFLT', 'dflt');
29 define('GN_ENUM_ISMULTI', 'multi');
30 define('GN_ENUM_TYPE', 'type');
31 define('GN_ENUM_MAX1', 'max1');
32 define('GN_ENUM_MAX2', 'max2');
33 define('GN_ENUM_MIN', 'min');
35 abstract class ApiBase
{
42 public function __construct($mainModule) {
43 $this->mMainModule
= $mainModule;
47 * Executes this module
49 abstract function execute();
54 public function getMain() {
55 return $this->mMainModule
;
59 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
61 public function isMain() {
62 return $this === $this->mMainModule
;
68 public function getResult() {
69 // Main module has getResult() method overriden
70 // Safety - avoid infinite loop:
72 $this->dieDebug(__METHOD__
.
73 ' base method was called on main module. ');
74 return $this->getMain()->getResult();
78 * Generates help message for this module, or false if there is no description
80 public function makeHelpMsg() {
82 static $lnPrfx = "\n ";
84 $msg = $this->getDescription();
92 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
95 $params = $this->getAllowedParams();
96 if ($params !== false) {
97 $paramsDescription = $this->getParamDescription();
98 $msg .= "Parameters:\n";
99 foreach (array_keys($params) as $paramName) {
100 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
102 $desc = implode("\n" . str_repeat(' ', 19), $desc);
103 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
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";
123 * Returns the description string for this module
125 protected function getDescription() {
130 * Returns usage examples for this module. Return null if no examples are available.
132 protected function getExamples() {
137 * Returns an array of allowed parameters (keys) => default value for that parameter
139 protected function getAllowedParams() {
144 * Returns the description string for the given parameter.
146 protected function getParamDescription() {
151 * Using getAllowedParams(), makes an array of the values provided by the user,
152 * with key being the name of the variable, and value - validated value from user or default.
153 * This method can be used to generate local variables using extract().
155 public function extractRequestParams() {
158 $params = $this->getAllowedParams();
161 foreach ($params as $param => $enumParams) {
163 if (!is_array($enumParams)) {
164 $default = $enumParams;
166 $type = gettype($enumParams);
168 $default = isset ($enumParams[GN_ENUM_DFLT
]) ?
$enumParams[GN_ENUM_DFLT
] : null;
169 $multi = isset ($enumParams[GN_ENUM_ISMULTI
]) ?
$enumParams[GN_ENUM_ISMULTI
] : false;
170 $type = isset ($enumParams[GN_ENUM_TYPE
]) ?
$enumParams[GN_ENUM_TYPE
] : null;
172 // When type is not given, and no choices, the type is the same as $default
173 if (!isset ($type)) {
174 if (isset ($default))
175 $type = gettype($default);
177 $type = 'NULL'; // allow everything
181 if ($type == 'boolean') {
182 if (!isset ($default))
185 if ($default !== false) {
186 // Having a default value of anything other than 'false' is pointless
187 $this->dieDebug("Boolean param $param's default is set to '$default'");
191 $value = $wgRequest->getVal($param, $default);
193 if (isset ($value) && ($multi ||
is_array($type)))
194 $value = $this->parseMultiValue($param, $value, $multi, is_array($type) ?
$type : null);
196 // More validation only when choices were not given
197 // choices were validated in parseMultiValue()
198 if (!is_array($type) && isset ($value)) {
201 case 'NULL' : // nothing to do
203 case 'string' : // nothing to do
205 case 'integer' : // Force everything using intval()
206 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
209 if (!isset ($enumParams[GN_ENUM_MAX1
]) ||
!isset ($enumParams[GN_ENUM_MAX2
]))
210 $this->dieDebug("MAX1 or MAX2 are not defined for the limit $param");
212 $this->dieDebug("Multi-values not supported for $param");
213 $min = isset ($enumParams[GN_ENUM_MIN
]) ?
$enumParams[GN_ENUM_MIN
] : 0;
214 $value = intval($value);
215 $this->validateLimit($param, $value, $min, $enumParams[GN_ENUM_MAX1
], $enumParams[GN_ENUM_MAX2
]);
219 $this->dieDebug("Multi-values not supported for $param");
220 $value = isset ($value);
224 $this->dieDebug("Multi-values not supported for $param");
225 $value = $this->prepareTimestamp($value); // Adds quotes around timestamp
228 $this->dieDebug("Param $param's type is unknown - $type");
233 $results[$param] = $value;
240 * Return an array of values that were given in a "a|b|c" notation,
241 * after it optionally validates them against the list allowed values.
243 * @param valueName - The name of the parameter (for error reporting)
244 * @param value - The value being parsed
245 * @param allowMultiple - Can $value contain more than one value separated by '|'?
246 * @param allowedValues - An array of values to check against. If null, all values are accepted.
247 * @return (allowMultiple ? an_array_of_values : a_single_value)
249 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
250 $valuesList = explode('|', $value);
251 if (!$allowMultiple && count($valuesList) != 1) {
252 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
253 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
255 if (is_array($allowedValues)) {
256 $unknownValues = array_diff($valuesList, $allowedValues);
257 if ($unknownValues) {
258 $this->dieUsage("Unrecognised value" . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
262 return $allowMultiple ?
$valuesList : $valuesList[0];
266 * Validate the proper format of the timestamp string (14 digits), and add quotes to it.
268 function prepareTimestamp($value) {
269 if (preg_match('/^[0-9]{14}$/', $value)) {
270 return $this->db
->addQuotes($value);
272 $this->dieUsage('Incorrect timestamp format', 'badtimestamp');
277 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
279 function validateLimit($varname, $value, $min, $max, $botMax) {
283 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
286 if ($this->getMain()->isBot()) {
287 if ($value > $botMax) {
288 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
292 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
298 * Call main module's error handler
300 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
301 $this->getMain()->mainDieUsage($description, $errorCode, $httpRespCode);
305 * Internal code errors should be reported with this method
307 protected function dieDebug($message) {
308 wfDebugDieBacktrace("Internal error in '{get_class($this)}': $message");
312 * Profiling: total module execution time
314 private $mTimeIn = 0, $mModuleTime = 0;
317 * Start module profiling
319 public function profileIn()
321 if ($this->mTimeIn
!== 0)
322 $this->dieDebug(__FUNCTION__
. ' called twice without calling profileOut()');
323 $this->mTimeIn
= microtime(true);
327 * End module profiling
329 public function profileOut()
331 if ($this->mTimeIn
=== 0)
332 $this->dieDebug(__FUNCTION__
. ' called without calling profileIn() first');
333 if ($this->mDBTimeIn
!== 0)
334 $this->dieDebug(__FUNCTION__
. ' must be called after database profiling is done with profileDBOut()');
336 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
341 * Total time the module was executed
343 public function getProfileTime()
345 if ($this->mTimeIn
!== 0)
346 $this->dieDebug(__FUNCTION__
. ' called without calling profileOut() first');
347 return $this->mModuleTime
;
351 * Profiling: database execution time
353 private $mDBTimeIn = 0, $mDBTime = 0;
356 * Start module profiling
358 public function profileDBIn()
360 if ($this->mTimeIn
=== 0)
361 $this->dieDebug(__FUNCTION__
. ' must be called while profiling the entire module with profileIn()');
362 if ($this->mDBTimeIn
!== 0)
363 $this->dieDebug(__FUNCTION__
. ' called twice without calling profileDBOut()');
364 $this->mDBTimeIn
= microtime(true);
368 * End database profiling
370 public function profileDBOut()
372 if ($this->mTimeIn
=== 0)
373 $this->dieDebug(__FUNCTION__
. ' must be called while profiling the entire module with profileIn()');
374 if ($this->mDBTimeIn
=== 0)
375 $this->dieDebug(__FUNCTION__
. ' called without calling profileDBIn() first');
377 $time = microtime(true) - $this->mDBTimeIn
;
378 $this->mDBTimeIn
= 0;
380 $this->mDBTime +
= $time;
381 $this->getMain()->mDBTime +
= $time;
385 * Total time the module used the database
387 public function getProfileDBTime()
389 if ($this->mDBTimeIn
!== 0)
390 $this->dieDebug(__FUNCTION__
. ' called without calling profileDBOut() first');
391 return $this->mDBTime
;