* API: implemented generator function
[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;
39
40 /**
41 * Constructor
42 */
43 public function __construct($mainModule) {
44 $this->mMainModule = $mainModule;
45 }
46
47 /**
48 * Executes this module
49 */
50 public abstract function execute();
51
52 /**
53 * Get main module
54 */
55 public function getMain() {
56 return $this->mMainModule;
57 }
58
59 /**
60 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
61 */
62 public function isMain() {
63 return $this === $this->mMainModule;
64 }
65
66 /**
67 * Get result object
68 */
69 public function getResult() {
70 // Main module has getResult() method overriden
71 // Safety - avoid infinite loop:
72 if ($this->isMain())
73 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
74 return $this->getMain()->getResult();
75 }
76
77 /**
78 * Get the result data array
79 */
80 public function & getResultData() {
81 return $this->getResult()->getData();
82 }
83
84 /**
85 * Generates help message for this module, or false if there is no description
86 */
87 public function makeHelpMsg() {
88
89 static $lnPrfx = "\n ";
90
91 $msg = $this->getDescription();
92
93 if ($msg !== false) {
94
95 if (!is_array($msg))
96 $msg = array (
97 $msg
98 );
99 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
100
101 // Parameters
102 $paramsMsg = $this->makeHelpMsgParameters();
103 if ($paramsMsg !== false) {
104 $msg .= "Parameters:\n$paramsMsg";
105 }
106
107 // Examples
108 $examples = $this->getExamples();
109 if ($examples !== false) {
110 if (!is_array($examples))
111 $examples = array (
112 $examples
113 );
114 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
115 $msg .= implode($lnPrfx, $examples) . "\n";
116 }
117
118 if ($this->getMain()->getShowVersions()) {
119 $versions = $this->getVersion();
120 if (is_array($versions))
121 $versions = implode("\n ", $versions);
122 $msg .= "Version:\n $versions\n";
123 }
124 }
125
126 return $msg;
127 }
128
129 public function makeHelpMsgParameters() {
130 $params = $this->getAllowedParams();
131 if ($params !== false) {
132
133 $paramsDescription = $this->getParamDescription();
134 $msg = '';
135 foreach (array_keys($params) as $paramName) {
136 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
137 if (is_array($desc))
138 $desc = implode("\n" . str_repeat(' ', 19), $desc);
139 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
140 }
141 return $msg;
142
143 } else
144 return false;
145 }
146
147 /**
148 * Returns the description string for this module
149 */
150 protected function getDescription() {
151 return false;
152 }
153
154 /**
155 * Returns usage examples for this module. Return null if no examples are available.
156 */
157 protected function getExamples() {
158 return false;
159 }
160
161 /**
162 * Returns an array of allowed parameters (keys) => default value for that parameter
163 */
164 protected function getAllowedParams() {
165 return false;
166 }
167
168 /**
169 * Returns the description string for the given parameter.
170 */
171 protected function getParamDescription() {
172 return false;
173 }
174
175 /**
176 * Using getAllowedParams(), makes an array of the values provided by the user,
177 * with key being the name of the variable, and value - validated value from user or default.
178 * This method can be used to generate local variables using extract().
179 *
180 * @param $prefix String: prepend this prefix to all parameter names.
181 */
182 public function extractRequestParams($prefix = '') {
183 $params = $this->getAllowedParams();
184 $results = array ();
185
186 foreach ($params as $paramName => $paramSettings)
187 $results[$paramName] = $this->getParameterFromSettings($prefix . $paramName, $paramSettings);
188
189 return $results;
190 }
191
192 protected function getParameter($paramName, $prefix = '') {
193 $params = $this->getAllowedParams();
194 $paramSettings = $params[$paramName];
195 return $this->getParameterFromSettings($prefix . $paramName, $paramSettings);
196 }
197
198 protected function getParameterFromSettings($paramName, $paramSettings) {
199 global $wgRequest;
200
201 if (!is_array($paramSettings)) {
202 $default = $paramSettings;
203 $multi = false;
204 $type = gettype($paramSettings);
205 } else {
206 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
207 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
208 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
209
210 // When type is not given, and no choices, the type is the same as $default
211 if (!isset ($type)) {
212 if (isset ($default))
213 $type = gettype($default);
214 else
215 $type = 'NULL'; // allow everything
216 }
217 }
218
219 if ($type == 'boolean') {
220 if (isset ($default) && $default !== false) {
221 // Having a default value of anything other than 'false' is pointless
222 ApiBase :: dieDebug(__METHOD__, "Boolean param $paramName's default is set to '$default'");
223 }
224
225 $value = $wgRequest->getCheck($paramName);
226 } else
227 $value = $wgRequest->getVal($paramName, $default);
228
229 if (isset ($value) && ($multi || is_array($type)))
230 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
231
232 // More validation only when choices were not given
233 // choices were validated in parseMultiValue()
234 if (!is_array($type) && isset ($value)) {
235
236 switch ($type) {
237 case 'NULL' : // nothing to do
238 break;
239 case 'string' : // nothing to do
240 break;
241 case 'integer' : // Force everything using intval()
242 $value = is_array($value) ? array_map('intval', $value) : intval($value);
243 break;
244 case 'limit' :
245 if (!isset ($paramSettings[self :: PARAM_MAX1]) || !isset ($paramSettings[self :: PARAM_MAX2]))
246 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $paramName");
247 if ($multi)
248 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
249 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
250 $value = intval($value);
251 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX1], $paramSettings[self :: PARAM_MAX2]);
252 break;
253 case 'boolean' :
254 if ($multi)
255 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
256 break;
257 case 'timestamp' :
258 if ($multi)
259 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
260 if (!preg_match('/^[0-9]{14}$/', $value))
261 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$valueName}");
262 break;
263 default :
264 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
265
266 }
267 }
268
269 return $value;
270 }
271
272 /**
273 * Return an array of values that were given in a 'a|b|c' notation,
274 * after it optionally validates them against the list allowed values.
275 *
276 * @param valueName - The name of the parameter (for error reporting)
277 * @param value - The value being parsed
278 * @param allowMultiple - Can $value contain more than one value separated by '|'?
279 * @param allowedValues - An array of values to check against. If null, all values are accepted.
280 * @return (allowMultiple ? an_array_of_values : a_single_value)
281 */
282 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
283 $valuesList = explode('|', $value);
284 if (!$allowMultiple && count($valuesList) != 1) {
285 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
286 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
287 }
288 if (is_array($allowedValues)) {
289 $unknownValues = array_diff($valuesList, $allowedValues);
290 if ($unknownValues) {
291 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
292 }
293 }
294
295 return $allowMultiple ? $valuesList : $valuesList[0];
296 }
297
298 /**
299 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
300 */
301 function validateLimit($varname, $value, $min, $max, $botMax) {
302 global $wgUser;
303
304 if ($value < $min) {
305 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
306 }
307
308 if ($this->getMain()->isBot()) {
309 if ($value > $botMax) {
310 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
311 }
312 }
313 elseif ($value > $max) {
314 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
315 }
316 }
317
318 /**
319 * Call main module's error handler
320 */
321 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
322 $this->getMain()->mainDieUsage($description, $errorCode, $httpRespCode);
323 }
324
325 /**
326 * Internal code errors should be reported with this method
327 */
328 protected static function dieDebug($method, $message) {
329 wfDebugDieBacktrace("Internal error in $method: $message");
330 }
331
332 /**
333 * Profiling: total module execution time
334 */
335 private $mTimeIn = 0, $mModuleTime = 0;
336
337 /**
338 * Start module profiling
339 */
340 public function profileIn() {
341 if ($this->mTimeIn !== 0)
342 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
343 $this->mTimeIn = microtime(true);
344 }
345
346 /**
347 * End module profiling
348 */
349 public function profileOut() {
350 if ($this->mTimeIn === 0)
351 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
352 if ($this->mDBTimeIn !== 0)
353 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
354
355 $this->mModuleTime += microtime(true) - $this->mTimeIn;
356 $this->mTimeIn = 0;
357 }
358
359 /**
360 * Total time the module was executed
361 */
362 public function getProfileTime() {
363 if ($this->mTimeIn !== 0)
364 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
365 return $this->mModuleTime;
366 }
367
368 /**
369 * Profiling: database execution time
370 */
371 private $mDBTimeIn = 0, $mDBTime = 0;
372
373 /**
374 * Start module profiling
375 */
376 public function profileDBIn() {
377 if ($this->mTimeIn === 0)
378 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
379 if ($this->mDBTimeIn !== 0)
380 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
381 $this->mDBTimeIn = microtime(true);
382 }
383
384 /**
385 * End database profiling
386 */
387 public function profileDBOut() {
388 if ($this->mTimeIn === 0)
389 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
390 if ($this->mDBTimeIn === 0)
391 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
392
393 $time = microtime(true) - $this->mDBTimeIn;
394 $this->mDBTimeIn = 0;
395
396 $this->mDBTime += $time;
397 $this->getMain()->mDBTime += $time;
398 }
399
400 /**
401 * Total time the module used the database
402 */
403 public function getProfileDBTime() {
404 if ($this->mDBTimeIn !== 0)
405 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
406 return $this->mDBTime;
407 }
408
409 public abstract function getVersion();
410
411 public static function getBaseVersion() {
412 return __CLASS__ . ': $Id$';
413 }
414 }
415 ?>