API * version param now links to the SVN
[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 const LIMIT_BIG1 = 500; // Fast query, user's limit
39 const LIMIT_BIG2 = 5000; // Fast query, bot's limit
40 const LIMIT_SML1 = 50; // Slow query, user's limit
41 const LIMIT_SML2 = 500; // Slow query, bot's limit
42
43 private $mMainModule, $mModuleName, $mParamPrefix;
44
45 /**
46 * Constructor
47 */
48 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
49 $this->mMainModule = $mainModule;
50 $this->mModuleName = $moduleName;
51 $this->mParamPrefix = $paramPrefix;
52 }
53
54 /**
55 * Executes this module
56 */
57 public abstract function execute();
58
59 /**
60 * Get the name of the module being executed by this instance
61 */
62 public function getModuleName() {
63 return $this->mModuleName;
64 }
65
66 /**
67 * Get the name of the module as shown in the profiler log
68 */
69 public function getModuleProfileName($db = false) {
70 if ($db)
71 return 'API:' . $this->mModuleName . '-DB';
72 else
73 return 'API:' . $this->mModuleName;
74 }
75
76 /**
77 * Get main module
78 */
79 public function getMain() {
80 return $this->mMainModule;
81 }
82
83 /**
84 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
85 */
86 public function isMain() {
87 return $this === $this->mMainModule;
88 }
89
90 /**
91 * Get result object
92 */
93 public function getResult() {
94 // Main module has getResult() method overriden
95 // Safety - avoid infinite loop:
96 if ($this->isMain())
97 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
98 return $this->getMain()->getResult();
99 }
100
101 /**
102 * Get the result data array
103 */
104 public function & getResultData() {
105 return $this->getResult()->getData();
106 }
107
108 /**
109 * If the module may only be used with a certain format module,
110 * it should override this method to return an instance of that formatter.
111 * A value of null means the default format will be used.
112 */
113 public function getCustomPrinter() {
114 return null;
115 }
116
117 /**
118 * Generates help message for this module, or false if there is no description
119 */
120 public function makeHelpMsg() {
121
122 static $lnPrfx = "\n ";
123
124 $msg = $this->getDescription();
125
126 if ($msg !== false) {
127
128 if (!is_array($msg))
129 $msg = array (
130 $msg
131 );
132 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
133
134 // Parameters
135 $paramsMsg = $this->makeHelpMsgParameters();
136 if ($paramsMsg !== false) {
137 $msg .= "Parameters:\n$paramsMsg";
138 }
139
140 // Examples
141 $examples = $this->getExamples();
142 if ($examples !== false) {
143 if (!is_array($examples))
144 $examples = array (
145 $examples
146 );
147 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
148 $msg .= implode($lnPrfx, $examples) . "\n";
149 }
150
151 if ($this->getMain()->getShowVersions()) {
152 $versions = $this->getVersion();
153 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
154 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
155
156 if (is_array($versions)) {
157 $ver2 = array();
158 foreach ($versions as &$v)
159 $v = eregi_replace($pattern, $replacement, $v);
160 $versions = implode("\n ", $versions);
161 }
162 else
163 $versions = eregi_replace($pattern, $replacement, $versions);
164
165 $msg .= "Version:\n $versions\n";
166 }
167 }
168
169 return $msg;
170 }
171
172 public function makeHelpMsgParameters() {
173 $params = $this->getAllowedParams();
174 if ($params !== false) {
175
176 $paramsDescription = $this->getParamDescription();
177 $msg = '';
178 $paramPrefix = "\n" . str_repeat(' ', 19);
179 foreach ($params as $paramName => $paramSettings) {
180 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
181 if (is_array($desc))
182 $desc = implode($paramPrefix, $desc);
183
184 @ $type = $paramSettings[self :: PARAM_TYPE];
185 if (isset ($type)) {
186 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
187 $prompt = 'Values (separate with \'|\'): ';
188 else
189 $prompt = 'One value: ';
190
191 if (is_array($type)) {
192 $desc .= $paramPrefix . $prompt . implode(', ', $type);
193 }
194 elseif ($type == 'namespace') {
195 // Special handling because namespaces are type-limited, yet they are not given
196 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
197 }
198 }
199
200 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
201 if (!is_null($default) && $default !== false)
202 $desc .= $paramPrefix . "Default: $default";
203
204 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
205 }
206 return $msg;
207
208 } else
209 return false;
210 }
211
212 /**
213 * Returns the description string for this module
214 */
215 protected function getDescription() {
216 return false;
217 }
218
219 /**
220 * Returns usage examples for this module. Return null if no examples are available.
221 */
222 protected function getExamples() {
223 return false;
224 }
225
226 /**
227 * Returns an array of allowed parameters (keys) => default value for that parameter
228 */
229 protected function getAllowedParams() {
230 return false;
231 }
232
233 /**
234 * Returns the description string for the given parameter.
235 */
236 protected function getParamDescription() {
237 return false;
238 }
239
240 /**
241 * This method mangles parameter name based on the prefix supplied to the constructor.
242 * Override this method to change parameter name during runtime
243 */
244 public function encodeParamName($paramName) {
245 return $this->mParamPrefix . $paramName;
246 }
247
248 /**
249 * Using getAllowedParams(), makes an array of the values provided by the user,
250 * with key being the name of the variable, and value - validated value from user or default.
251 * This method can be used to generate local variables using extract().
252 */
253 public function extractRequestParams() {
254 $params = $this->getAllowedParams();
255 $results = array ();
256
257 foreach ($params as $paramName => $paramSettings)
258 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
259
260 return $results;
261 }
262
263 /**
264 * Get a value for the given parameter
265 */
266 protected function getParameter($paramName) {
267 $params = $this->getAllowedParams();
268 $paramSettings = $params[$paramName];
269 return $this->getParameterFromSettings($paramName, $paramSettings);
270 }
271
272 public static function getValidNamespaces() {
273 static $mValidNamespaces = null;
274 if (is_null($mValidNamespaces)) {
275
276 global $wgContLang;
277 $mValidNamespaces = array ();
278 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
279 if ($ns >= 0)
280 $mValidNamespaces[] = $ns;
281 }
282 }
283 return $mValidNamespaces;
284 }
285
286 /**
287 * Using the settings determine the value for the given parameter
288 * @param $paramName String: parameter name
289 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
290 */
291 protected function getParameterFromSettings($paramName, $paramSettings) {
292
293 // Some classes may decide to change parameter names
294 $paramName = $this->encodeParamName($paramName);
295
296 if (!is_array($paramSettings)) {
297 $default = $paramSettings;
298 $multi = false;
299 $type = gettype($paramSettings);
300 } else {
301 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
302 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
303 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
304
305 // When type is not given, and no choices, the type is the same as $default
306 if (!isset ($type)) {
307 if (isset ($default))
308 $type = gettype($default);
309 else
310 $type = 'NULL'; // allow everything
311 }
312 }
313
314 if ($type == 'boolean') {
315 if (isset ($default) && $default !== false) {
316 // Having a default value of anything other than 'false' is pointless
317 ApiBase :: dieDebug(__METHOD__, "Boolean param $paramName's default is set to '$default'");
318 }
319
320 $value = $this->getMain()->getRequest()->getCheck($paramName);
321 } else {
322 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
323
324 if (isset ($value) && $type == 'namespace')
325 $type = ApiBase :: getValidNamespaces();
326 }
327
328 if (isset ($value) && ($multi || is_array($type)))
329 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
330
331 // More validation only when choices were not given
332 // choices were validated in parseMultiValue()
333 if (isset ($value)) {
334 if (!is_array($type)) {
335 switch ($type) {
336 case 'NULL' : // nothing to do
337 break;
338 case 'string' : // nothing to do
339 break;
340 case 'integer' : // Force everything using intval()
341 $value = is_array($value) ? array_map('intval', $value) : intval($value);
342 break;
343 case 'limit' :
344 if (!isset ($paramSettings[self :: PARAM_MAX1]) || !isset ($paramSettings[self :: PARAM_MAX2]))
345 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $paramName");
346 if ($multi)
347 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
348 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
349 $value = intval($value);
350 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX1], $paramSettings[self :: PARAM_MAX2]);
351 break;
352 case 'boolean' :
353 if ($multi)
354 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
355 break;
356 case 'timestamp' :
357 if ($multi)
358 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
359 $value = wfTimestamp(TS_UNIX, $value);
360 if ($value === 0)
361 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
362 $value = wfTimestamp(TS_MW, $value);
363 break;
364 default :
365 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
366 }
367 }
368
369 // There should never be any duplicate values in a list
370 if (is_array($value))
371 $value = array_unique($value);
372 }
373
374 return $value;
375 }
376
377 /**
378 * Return an array of values that were given in a 'a|b|c' notation,
379 * after it optionally validates them against the list allowed values.
380 *
381 * @param valueName - The name of the parameter (for error reporting)
382 * @param value - The value being parsed
383 * @param allowMultiple - Can $value contain more than one value separated by '|'?
384 * @param allowedValues - An array of values to check against. If null, all values are accepted.
385 * @return (allowMultiple ? an_array_of_values : a_single_value)
386 */
387 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
388 $valuesList = explode('|', $value);
389 if (!$allowMultiple && count($valuesList) != 1) {
390 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
391 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
392 }
393 if (is_array($allowedValues)) {
394 $unknownValues = array_diff($valuesList, $allowedValues);
395 if ($unknownValues) {
396 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
397 }
398 }
399
400 return $allowMultiple ? $valuesList : $valuesList[0];
401 }
402
403 /**
404 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
405 */
406 function validateLimit($varname, $value, $min, $max, $botMax) {
407 if ($value < $min) {
408 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
409 }
410
411 if ($this->getMain()->isBot()) {
412 if ($value > $botMax) {
413 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
414 }
415 }
416 elseif ($value > $max) {
417 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
418 }
419 }
420
421 /**
422 * Call main module's error handler
423 */
424 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
425 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
426 }
427
428 /**
429 * Internal code errors should be reported with this method
430 */
431 protected static function dieDebug($method, $message) {
432 wfDebugDieBacktrace("Internal error in $method: $message");
433 }
434
435 /**
436 * Profiling: total module execution time
437 */
438 private $mTimeIn = 0, $mModuleTime = 0;
439
440 /**
441 * Start module profiling
442 */
443 public function profileIn() {
444 if ($this->mTimeIn !== 0)
445 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
446 $this->mTimeIn = microtime(true);
447 wfProfileIn($this->getModuleProfileName());
448 }
449
450 /**
451 * End module profiling
452 */
453 public function profileOut() {
454 if ($this->mTimeIn === 0)
455 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
456 if ($this->mDBTimeIn !== 0)
457 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
458
459 $this->mModuleTime += microtime(true) - $this->mTimeIn;
460 $this->mTimeIn = 0;
461 wfProfileOut($this->getModuleProfileName());
462 }
463
464 /**
465 * When modules crash, sometimes it is needed to do a profileOut() regardless
466 * of the profiling state the module was in. This method does such cleanup.
467 */
468 public function safeProfileOut() {
469 if ($this->mTimeIn !== 0) {
470 if ($this->mDBTimeIn !== 0)
471 $this->profileDBOut();
472 $this->profileOut();
473 }
474 }
475
476 /**
477 * Total time the module was executed
478 */
479 public function getProfileTime() {
480 if ($this->mTimeIn !== 0)
481 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
482 return $this->mModuleTime;
483 }
484
485 /**
486 * Profiling: database execution time
487 */
488 private $mDBTimeIn = 0, $mDBTime = 0;
489
490 /**
491 * Start module profiling
492 */
493 public function profileDBIn() {
494 if ($this->mTimeIn === 0)
495 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
496 if ($this->mDBTimeIn !== 0)
497 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
498 $this->mDBTimeIn = microtime(true);
499 wfProfileIn($this->getModuleProfileName(true));
500 }
501
502 /**
503 * End database profiling
504 */
505 public function profileDBOut() {
506 if ($this->mTimeIn === 0)
507 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
508 if ($this->mDBTimeIn === 0)
509 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
510
511 $time = microtime(true) - $this->mDBTimeIn;
512 $this->mDBTimeIn = 0;
513
514 $this->mDBTime += $time;
515 $this->getMain()->mDBTime += $time;
516 wfProfileOut($this->getModuleProfileName(true));
517 }
518
519 /**
520 * Total time the module used the database
521 */
522 public function getProfileDBTime() {
523 if ($this->mDBTimeIn !== 0)
524 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
525 return $this->mDBTime;
526 }
527
528 public abstract function getVersion();
529
530 public static function getBaseVersion() {
531 return __CLASS__ . ': $Id$';
532 }
533 }
534 ?>