c3ce8e511f1419aad89ade636fefc1acf40b7cb8
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 $paramsMsg = $this->makeHelpMsgParameters();
96 if ($paramsMsg !== false) {
97 $msg .= "Parameters:\n$paramsMsg";
101 $examples = $this->getExamples();
102 if ($examples !== false) {
103 if (!is_array($examples))
107 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
108 $msg .= implode($lnPrfx, $examples) . "\n";
115 public function makeHelpMsgParameters() {
116 $params = $this->getAllowedParams();
117 if ($params !== false) {
119 $paramsDescription = $this->getParamDescription();
121 foreach (array_keys($params) as $paramName) {
122 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
124 $desc = implode("\n" . str_repeat(' ', 19), $desc);
125 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
135 * Returns the description string for this module
137 protected function getDescription() {
142 * Returns usage examples for this module. Return null if no examples are available.
144 protected function getExamples() {
149 * Returns an array of allowed parameters (keys) => default value for that parameter
151 protected function getAllowedParams() {
156 * Returns the description string for the given parameter.
158 protected function getParamDescription() {
163 * Using getAllowedParams(), makes an array of the values provided by the user,
164 * with key being the name of the variable, and value - validated value from user or default.
165 * This method can be used to generate local variables using extract().
167 public function extractRequestParams() {
168 $params = $this->getAllowedParams();
171 foreach ($params as $paramName => $paramSettings)
172 $results[$paramName] = $this->getParameter($paramName, $paramSettings);
177 public function getParameter($paramName, $paramSettings){
180 if (!is_array($paramSettings)) {
181 $default = $paramSettings;
183 $type = gettype($paramSettings);
185 $default = isset ($paramSettings[GN_ENUM_DFLT
]) ?
$paramSettings[GN_ENUM_DFLT
] : null;
186 $multi = isset ($paramSettings[GN_ENUM_ISMULTI
]) ?
$paramSettings[GN_ENUM_ISMULTI
] : false;
187 $type = isset ($paramSettings[GN_ENUM_TYPE
]) ?
$paramSettings[GN_ENUM_TYPE
] : null;
189 // When type is not given, and no choices, the type is the same as $default
190 if (!isset ($type)) {
191 if (isset ($default))
192 $type = gettype($default);
194 $type = 'NULL'; // allow everything
198 if ($type == 'boolean') {
199 if (isset ($default) && $default !== false) {
200 // Having a default value of anything other than 'false' is pointless
201 $this->dieDebug("Boolean param $paramName's default is set to '$default'");
204 $value = $wgRequest->getCheck($paramName);
206 $value = $wgRequest->getVal($paramName, $default);
208 if (isset ($value) && ($multi ||
is_array($type)))
209 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
211 // More validation only when choices were not given
212 // choices were validated in parseMultiValue()
213 if (!is_array($type) && isset ($value)) {
216 case 'NULL' : // nothing to do
218 case 'string' : // nothing to do
220 case 'integer' : // Force everything using intval()
221 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
224 if (!isset ($paramSettings[GN_ENUM_MAX1
]) ||
!isset ($paramSettings[GN_ENUM_MAX2
]))
225 $this->dieDebug("MAX1 or MAX2 are not defined for the limit $paramName");
227 $this->dieDebug("Multi-values not supported for $paramName");
228 $min = isset ($paramSettings[GN_ENUM_MIN
]) ?
$paramSettings[GN_ENUM_MIN
] : 0;
229 $value = intval($value);
230 $this->validateLimit($paramName, $value, $min, $paramSettings[GN_ENUM_MAX1
], $paramSettings[GN_ENUM_MAX2
]);
234 $this->dieDebug("Multi-values not supported for $paramName");
238 $this->dieDebug("Multi-values not supported for $paramName");
239 $value = $this->prepareTimestamp($value); // Adds quotes around timestamp
242 $this->dieDebug("Param $paramName's type is unknown - $type");
251 * Return an array of values that were given in a "a|b|c" notation,
252 * after it optionally validates them against the list allowed values.
254 * @param valueName - The name of the parameter (for error reporting)
255 * @param value - The value being parsed
256 * @param allowMultiple - Can $value contain more than one value separated by '|'?
257 * @param allowedValues - An array of values to check against. If null, all values are accepted.
258 * @return (allowMultiple ? an_array_of_values : a_single_value)
260 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
261 $valuesList = explode('|', $value);
262 if (!$allowMultiple && count($valuesList) != 1) {
263 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
264 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
266 if (is_array($allowedValues)) {
267 $unknownValues = array_diff($valuesList, $allowedValues);
268 if ($unknownValues) {
269 $this->dieUsage("Unrecognised value" . (count($unknownValues) > 1 ?
"s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
273 return $allowMultiple ?
$valuesList : $valuesList[0];
277 * Validate the proper format of the timestamp string (14 digits), and add quotes to it.
279 function prepareTimestamp($value) {
280 if (preg_match('/^[0-9]{14}$/', $value)) {
281 return $this->db
->addQuotes($value);
283 $this->dieUsage('Incorrect timestamp format', 'badtimestamp');
288 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
290 function validateLimit($varname, $value, $min, $max, $botMax) {
294 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
297 if ($this->getMain()->isBot()) {
298 if ($value > $botMax) {
299 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
303 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
309 * Call main module's error handler
311 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
312 $this->getMain()->mainDieUsage($description, $errorCode, $httpRespCode);
316 * Internal code errors should be reported with this method
318 protected function dieDebug($message) {
319 wfDebugDieBacktrace("Internal error in '{get_class($this)}': $message");
323 * Profiling: total module execution time
325 private $mTimeIn = 0, $mModuleTime = 0;
328 * Start module profiling
330 public function profileIn()
332 if ($this->mTimeIn
!== 0)
333 $this->dieDebug(__FUNCTION__
. ' called twice without calling profileOut()');
334 $this->mTimeIn
= microtime(true);
338 * End module profiling
340 public function profileOut()
342 if ($this->mTimeIn
=== 0)
343 $this->dieDebug(__FUNCTION__
. ' called without calling profileIn() first');
344 if ($this->mDBTimeIn
!== 0)
345 $this->dieDebug(__FUNCTION__
. ' 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()
356 if ($this->mTimeIn
!== 0)
357 $this->dieDebug(__FUNCTION__
. ' called without calling profileOut() first');
358 return $this->mModuleTime
;
362 * Profiling: database execution time
364 private $mDBTimeIn = 0, $mDBTime = 0;
367 * Start module profiling
369 public function profileDBIn()
371 if ($this->mTimeIn
=== 0)
372 $this->dieDebug(__FUNCTION__
. ' must be called while profiling the entire module with profileIn()');
373 if ($this->mDBTimeIn
!== 0)
374 $this->dieDebug(__FUNCTION__
. ' called twice without calling profileDBOut()');
375 $this->mDBTimeIn
= microtime(true);
379 * End database profiling
381 public function profileDBOut()
383 if ($this->mTimeIn
=== 0)
384 $this->dieDebug(__FUNCTION__
. ' must be called while profiling the entire module with profileIn()');
385 if ($this->mDBTimeIn
=== 0)
386 $this->dieDebug(__FUNCTION__
. ' called without calling profileDBIn() first');
388 $time = microtime(true) - $this->mDBTimeIn
;
389 $this->mDBTimeIn
= 0;
391 $this->mDBTime +
= $time;
392 $this->getMain()->mDBTime +
= $time;
396 * Total time the module used the database
398 public function getProfileDBTime()
400 if ($this->mDBTimeIn
!== 0)
401 $this->dieDebug(__FUNCTION__
. ' called without calling profileDBOut() first');
402 return $this->mDBTime
;