* API: help screen now shows default and allowed parameter values
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2
3
4 /*
5 * Created on Sep 5, 2006
6 *
7 * API for MediaWiki 1.8+
8 *
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
10 *
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.
15 *
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.
20 *
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
25 */
26
27 abstract class ApiBase {
28
29 // These constants allow modules to specify exactly how to treat incomming parameters.
30
31 const PARAM_DFLT = 0;
32 const PARAM_ISMULTI = 1;
33 const PARAM_TYPE = 2;
34 const PARAM_MAX1 = 3;
35 const PARAM_MAX2 = 4;
36 const PARAM_MIN = 5;
37
38 private $mMainModule, $mModuleName, $mParamPrefix;
39
40 /**
41 * Constructor
42 */
43 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
44 $this->mMainModule = $mainModule;
45 $this->mModuleName = $moduleName;
46 $this->mParamPrefix = $paramPrefix;
47 }
48
49 /**
50 * Executes this module
51 */
52 public abstract function execute();
53
54 /**
55 * Get the name of the query being executed by this instance
56 */
57 public function getModuleName() {
58 return $this->mModuleName;
59 }
60
61 /**
62 * Get main module
63 */
64 public function getMain() {
65 return $this->mMainModule;
66 }
67
68 /**
69 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
70 */
71 public function isMain() {
72 return $this === $this->mMainModule;
73 }
74
75 /**
76 * Get result object
77 */
78 public function getResult() {
79 // Main module has getResult() method overriden
80 // Safety - avoid infinite loop:
81 if ($this->isMain())
82 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
83 return $this->getMain()->getResult();
84 }
85
86 /**
87 * Get the result data array
88 */
89 public function & getResultData() {
90 return $this->getResult()->getData();
91 }
92
93 /**
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.
97 */
98 public function getCustomPrinter() {
99 return null;
100 }
101
102 /**
103 * Generates help message for this module, or false if there is no description
104 */
105 public function makeHelpMsg() {
106
107 static $lnPrfx = "\n ";
108
109 $msg = $this->getDescription();
110
111 if ($msg !== false) {
112
113 if (!is_array($msg))
114 $msg = array (
115 $msg
116 );
117 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
118
119 // Parameters
120 $paramsMsg = $this->makeHelpMsgParameters();
121 if ($paramsMsg !== false) {
122 $msg .= "Parameters:\n$paramsMsg";
123 }
124
125 // Examples
126 $examples = $this->getExamples();
127 if ($examples !== false) {
128 if (!is_array($examples))
129 $examples = array (
130 $examples
131 );
132 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
133 $msg .= implode($lnPrfx, $examples) . "\n";
134 }
135
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";
141 }
142 }
143
144 return $msg;
145 }
146
147 public function makeHelpMsgParameters() {
148 $params = $this->getAllowedParams();
149 if ($params !== false) {
150
151 $paramsDescription = $this->getParamDescription();
152 $msg = '';
153 $paramPrefix = "\n" . str_repeat(' ', 19);
154 foreach ($params as $paramName => &$paramSettings) {
155 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
156 if (is_array($desc))
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);
162 }
163 }
164
165 $default = is_array($paramSettings)
166 ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null)
167 : $paramSettings;
168 if (!is_null($default) && $default !== false)
169 $desc .= $paramPrefix . "Default: $default";
170
171 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
172 }
173 return $msg;
174
175 } else
176 return false;
177 }
178
179 /**
180 * Returns the description string for this module
181 */
182 protected function getDescription() {
183 return false;
184 }
185
186 /**
187 * Returns usage examples for this module. Return null if no examples are available.
188 */
189 protected function getExamples() {
190 return false;
191 }
192
193 /**
194 * Returns an array of allowed parameters (keys) => default value for that parameter
195 */
196 protected function getAllowedParams() {
197 return false;
198 }
199
200 /**
201 * Returns the description string for the given parameter.
202 */
203 protected function getParamDescription() {
204 return false;
205 }
206
207 /**
208 * This method mangles parameter name based on the prefix supplied to the constructor.
209 * Override this method to change parameter name during runtime
210 */
211 public function encodeParamName($paramName) {
212 return $this->mParamPrefix . $paramName;
213 }
214
215 /**
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().
219 */
220 public function extractRequestParams() {
221 $params = $this->getAllowedParams();
222 $results = array ();
223
224 foreach ($params as $paramName => $paramSettings)
225 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
226
227 return $results;
228 }
229
230 /**
231 * Get a value for the given parameter
232 */
233 protected function getParameter($paramName) {
234 $params = $this->getAllowedParams();
235 $paramSettings = $params[$paramName];
236 return $this->getParameterFromSettings($paramName, $paramSettings);
237 }
238
239 /**
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.
243 */
244 protected function getParameterFromSettings($paramName, $paramSettings) {
245
246 // Some classes may decide to change parameter names
247 $paramName = $this->encodeParamName($paramName);
248
249 if (!is_array($paramSettings)) {
250 $default = $paramSettings;
251 $multi = false;
252 $type = gettype($paramSettings);
253 } else {
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;
257
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);
262 else
263 $type = 'NULL'; // allow everything
264 }
265 }
266
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'");
271 }
272
273 $value = $this->getMain()->getRequest()->getCheck($paramName);
274 } else {
275 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
276 }
277
278 if (isset ($value) && ($multi || is_array($type)))
279 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
280
281 // More validation only when choices were not given
282 // choices were validated in parseMultiValue()
283 if (!is_array($type) && isset ($value)) {
284
285 switch ($type) {
286 case 'NULL' : // nothing to do
287 break;
288 case 'string' : // nothing to do
289 break;
290 case 'integer' : // Force everything using intval()
291 $value = is_array($value) ? array_map('intval', $value) : intval($value);
292 break;
293 case 'limit' :
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");
296 if ($multi)
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]);
301 break;
302 case 'boolean' :
303 if ($multi)
304 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
305 break;
306 case 'timestamp' :
307 if ($multi)
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}");
311 break;
312 default :
313 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
314
315 }
316 }
317
318 // There should never be any duplicate values in a list
319 if (is_array($value))
320 $value = array_unique($value);
321
322 return $value;
323 }
324
325 /**
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.
328 *
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)
334 */
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");
340 }
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");
345 }
346 }
347
348 return $allowMultiple ? $valuesList : $valuesList[0];
349 }
350
351 /**
352 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
353 */
354 function validateLimit($varname, $value, $min, $max, $botMax) {
355 global $wgUser;
356
357 if ($value < $min) {
358 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
359 }
360
361 if ($this->getMain()->isBot()) {
362 if ($value > $botMax) {
363 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
364 }
365 }
366 elseif ($value > $max) {
367 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
368 }
369 }
370
371 /**
372 * Call main module's error handler
373 */
374 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
375 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
376 }
377
378 /**
379 * Internal code errors should be reported with this method
380 */
381 protected static function dieDebug($method, $message) {
382 wfDebugDieBacktrace("Internal error in $method: $message");
383 }
384
385 /**
386 * Profiling: total module execution time
387 */
388 private $mTimeIn = 0, $mModuleTime = 0;
389
390 /**
391 * Start module profiling
392 */
393 public function profileIn() {
394 if ($this->mTimeIn !== 0)
395 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
396 $this->mTimeIn = microtime(true);
397 }
398
399 /**
400 * End module profiling
401 */
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()');
407
408 $this->mModuleTime += microtime(true) - $this->mTimeIn;
409 $this->mTimeIn = 0;
410 }
411
412 /**
413 * Total time the module was executed
414 */
415 public function getProfileTime() {
416 if ($this->mTimeIn !== 0)
417 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
418 return $this->mModuleTime;
419 }
420
421 /**
422 * Profiling: database execution time
423 */
424 private $mDBTimeIn = 0, $mDBTime = 0;
425
426 /**
427 * Start module profiling
428 */
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);
435 }
436
437 /**
438 * End database profiling
439 */
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');
445
446 $time = microtime(true) - $this->mDBTimeIn;
447 $this->mDBTimeIn = 0;
448
449 $this->mDBTime += $time;
450 $this->getMain()->mDBTime += $time;
451 }
452
453 /**
454 * Total time the module used the database
455 */
456 public function getProfileDBTime() {
457 if ($this->mDBTimeIn !== 0)
458 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
459 return $this->mDBTime;
460 }
461
462 public abstract function getVersion();
463
464 public static function getBaseVersion() {
465 return __CLASS__ . ': $Id$';
466 }
467 }
468 ?>