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