9e000a05fee83ccee096f9178106a766a47ba553
[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 getCustomFormatModule() {
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 foreach (array_keys($params) as $paramName) {
154 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
155 if (is_array($desc))
156 $desc = implode("\n" . str_repeat(' ', 19), $desc);
157 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
158 }
159 return $msg;
160
161 } else
162 return false;
163 }
164
165 /**
166 * Returns the description string for this module
167 */
168 protected function getDescription() {
169 return false;
170 }
171
172 /**
173 * Returns usage examples for this module. Return null if no examples are available.
174 */
175 protected function getExamples() {
176 return false;
177 }
178
179 /**
180 * Returns an array of allowed parameters (keys) => default value for that parameter
181 */
182 protected function getAllowedParams() {
183 return false;
184 }
185
186 /**
187 * Returns the description string for the given parameter.
188 */
189 protected function getParamDescription() {
190 return false;
191 }
192
193 /**
194 * This method mangles parameter name based on the prefix supplied to the constructor.
195 * Override this method to change parameter name during runtime
196 */
197 public function encodeParamName($paramName) {
198 return $this->mParamPrefix . $paramName;
199 }
200
201 /**
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().
205 */
206 public function extractRequestParams() {
207 $params = $this->getAllowedParams();
208 $results = array ();
209
210 foreach ($params as $paramName => $paramSettings)
211 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
212
213 return $results;
214 }
215
216 /**
217 * Get a value for the given parameter
218 */
219 protected function getParameter($paramName) {
220 $params = $this->getAllowedParams();
221 $paramSettings = $params[$paramName];
222 return $this->getParameterFromSettings($paramName, $paramSettings);
223 }
224
225 /**
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.
229 */
230 protected function getParameterFromSettings($paramName, $paramSettings) {
231
232 // Some classes may decide to change parameter names
233 $paramName = $this->encodeParamName($paramName);
234
235 if (!is_array($paramSettings)) {
236 $default = $paramSettings;
237 $multi = false;
238 $type = gettype($paramSettings);
239 } else {
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;
243
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);
248 else
249 $type = 'NULL'; // allow everything
250 }
251 }
252
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'");
257 }
258
259 $value = $this->getMain()->getRequest()->getCheck($paramName);
260 } else {
261 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
262 }
263
264 if (isset ($value) && ($multi || is_array($type)))
265 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
266
267 // More validation only when choices were not given
268 // choices were validated in parseMultiValue()
269 if (!is_array($type) && isset ($value)) {
270
271 switch ($type) {
272 case 'NULL' : // nothing to do
273 break;
274 case 'string' : // nothing to do
275 break;
276 case 'integer' : // Force everything using intval()
277 $value = is_array($value) ? array_map('intval', $value) : intval($value);
278 break;
279 case 'limit' :
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");
282 if ($multi)
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]);
287 break;
288 case 'boolean' :
289 if ($multi)
290 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
291 break;
292 case 'timestamp' :
293 if ($multi)
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}");
297 break;
298 default :
299 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
300
301 }
302 }
303
304 // There should never be any duplicate values in a list
305 if (is_array($value))
306 $value = array_unique($value);
307
308 return $value;
309 }
310
311 /**
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.
314 *
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)
320 */
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");
326 }
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");
331 }
332 }
333
334 return $allowMultiple ? $valuesList : $valuesList[0];
335 }
336
337 /**
338 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
339 */
340 function validateLimit($varname, $value, $min, $max, $botMax) {
341 global $wgUser;
342
343 if ($value < $min) {
344 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
345 }
346
347 if ($this->getMain()->isBot()) {
348 if ($value > $botMax) {
349 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
350 }
351 }
352 elseif ($value > $max) {
353 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
354 }
355 }
356
357 /**
358 * Call main module's error handler
359 */
360 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
361 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
362 }
363
364 /**
365 * Internal code errors should be reported with this method
366 */
367 protected static function dieDebug($method, $message) {
368 wfDebugDieBacktrace("Internal error in $method: $message");
369 }
370
371 /**
372 * Profiling: total module execution time
373 */
374 private $mTimeIn = 0, $mModuleTime = 0;
375
376 /**
377 * Start module profiling
378 */
379 public function profileIn() {
380 if ($this->mTimeIn !== 0)
381 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
382 $this->mTimeIn = microtime(true);
383 }
384
385 /**
386 * End module profiling
387 */
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()');
393
394 $this->mModuleTime += microtime(true) - $this->mTimeIn;
395 $this->mTimeIn = 0;
396 }
397
398 /**
399 * Total time the module was executed
400 */
401 public function getProfileTime() {
402 if ($this->mTimeIn !== 0)
403 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
404 return $this->mModuleTime;
405 }
406
407 /**
408 * Profiling: database execution time
409 */
410 private $mDBTimeIn = 0, $mDBTime = 0;
411
412 /**
413 * Start module profiling
414 */
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);
421 }
422
423 /**
424 * End database profiling
425 */
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');
431
432 $time = microtime(true) - $this->mDBTimeIn;
433 $this->mDBTimeIn = 0;
434
435 $this->mDBTime += $time;
436 $this->getMain()->mDBTime += $time;
437 }
438
439 /**
440 * Total time the module used the database
441 */
442 public function getProfileDBTime() {
443 if ($this->mDBTimeIn !== 0)
444 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
445 return $this->mDBTime;
446 }
447
448 public abstract function getVersion();
449
450 public static function getBaseVersion() {
451 return __CLASS__ . ': $Id$';
452 }
453 }
454 ?>