API: documentation and cleanup.
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2
3 /*
4 * Created on Sep 5, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 /**
27 * This abstract class implements many basic API functions, and is the base of all API classes.
28 * The class functions are divided into several areas of functionality:
29 *
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
32 *
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
34 *
35 * Self-documentation: code to allow api to document its own state.
36 *
37 * @addtogroup API
38 */
39 abstract class ApiBase {
40
41 // These constants allow modules to specify exactly how to treat incomming parameters.
42
43 const PARAM_DFLT = 0;
44 const PARAM_ISMULTI = 1;
45 const PARAM_TYPE = 2;
46 const PARAM_MAX = 3;
47 const PARAM_MAX2 = 4;
48 const PARAM_MIN = 5;
49
50 const LIMIT_BIG1 = 500; // Fast query, user's limit
51 const LIMIT_BIG2 = 5000; // Fast query, bot's limit
52 const LIMIT_SML1 = 50; // Slow query, user's limit
53 const LIMIT_SML2 = 500; // Slow query, bot's limit
54
55 private $mMainModule, $mModuleName, $mParamPrefix;
56
57 /**
58 * Constructor
59 */
60 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
61 $this->mMainModule = $mainModule;
62 $this->mModuleName = $moduleName;
63 $this->mParamPrefix = $paramPrefix;
64 }
65
66 /**
67 * Executes this module
68 */
69 public abstract function execute();
70
71 /**
72 * Get the name of the module being executed by this instance
73 */
74 public function getModuleName() {
75 return $this->mModuleName;
76 }
77
78 /**
79 * Get the name of the module as shown in the profiler log
80 */
81 public function getModuleProfileName($db = false) {
82 if ($db)
83 return 'API:' . $this->mModuleName . '-DB';
84 else
85 return 'API:' . $this->mModuleName;
86 }
87
88 /**
89 * Get main module
90 */
91 public function getMain() {
92 return $this->mMainModule;
93 }
94
95 /**
96 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
97 */
98 public function isMain() {
99 return $this === $this->mMainModule;
100 }
101
102 /**
103 * Get result object
104 */
105 public function getResult() {
106 // Main module has getResult() method overriden
107 // Safety - avoid infinite loop:
108 if ($this->isMain())
109 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
110 return $this->getMain()->getResult();
111 }
112
113 /**
114 * Get the result data array
115 */
116 public function & getResultData() {
117 return $this->getResult()->getData();
118 }
119
120 /**
121 * If the module may only be used with a certain format module,
122 * it should override this method to return an instance of that formatter.
123 * A value of null means the default format will be used.
124 */
125 public function getCustomPrinter() {
126 return null;
127 }
128
129 /**
130 * Generates help message for this module, or false if there is no description
131 */
132 public function makeHelpMsg() {
133
134 static $lnPrfx = "\n ";
135
136 $msg = $this->getDescription();
137
138 if ($msg !== false) {
139
140 if (!is_array($msg))
141 $msg = array (
142 $msg
143 );
144 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
145
146 // Parameters
147 $paramsMsg = $this->makeHelpMsgParameters();
148 if ($paramsMsg !== false) {
149 $msg .= "Parameters:\n$paramsMsg";
150 }
151
152 // Examples
153 $examples = $this->getExamples();
154 if ($examples !== false) {
155 if (!is_array($examples))
156 $examples = array (
157 $examples
158 );
159 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
160 $msg .= implode($lnPrfx, $examples) . "\n";
161 }
162
163 if ($this->getMain()->getShowVersions()) {
164 $versions = $this->getVersion();
165 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
166 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
167
168 if (is_array($versions)) {
169 foreach ($versions as &$v)
170 $v = eregi_replace($pattern, $replacement, $v);
171 $versions = implode("\n ", $versions);
172 }
173 else
174 $versions = eregi_replace($pattern, $replacement, $versions);
175
176 $msg .= "Version:\n $versions\n";
177 }
178 }
179
180 return $msg;
181 }
182
183 public function makeHelpMsgParameters() {
184 $params = $this->getAllowedParams();
185 if ($params !== false) {
186
187 $paramsDescription = $this->getParamDescription();
188 $msg = '';
189 $paramPrefix = "\n" . str_repeat(' ', 19);
190 foreach ($params as $paramName => $paramSettings) {
191 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
192 if (is_array($desc))
193 $desc = implode($paramPrefix, $desc);
194
195 @ $type = $paramSettings[self :: PARAM_TYPE];
196 if (isset ($type)) {
197 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
198 $prompt = 'Values (separate with \'|\'): ';
199 else
200 $prompt = 'One value: ';
201
202 if (is_array($type)) {
203 $choices = array();
204 $nothingPrompt = false;
205 foreach ($type as $t)
206 if ($t=='')
207 $nothingPrompt = 'Can be empty, or ';
208 else
209 $choices[] = $t;
210 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
211 } else {
212 switch ($type) {
213 case 'namespace':
214 // Special handling because namespaces are type-limited, yet they are not given
215 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
216 break;
217 case 'limit':
218 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
219 break;
220 case 'integer':
221 $hasMin = isset($paramSettings[self :: PARAM_MIN]);
222 $hasMax = isset($paramSettings[self :: PARAM_MAX]);
223 if ($hasMin || $hasMax) {
224 if (!$hasMax)
225 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
226 elseif (!$hasMin)
227 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
228 else
229 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
230
231 $desc .= $paramPrefix . $intRangeStr;
232 }
233 break;
234 }
235 }
236 }
237
238 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
239 if (!is_null($default) && $default !== false)
240 $desc .= $paramPrefix . "Default: $default";
241
242 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
243 }
244 return $msg;
245
246 } else
247 return false;
248 }
249
250 /**
251 * Returns the description string for this module
252 */
253 protected function getDescription() {
254 return false;
255 }
256
257 /**
258 * Returns usage examples for this module. Return null if no examples are available.
259 */
260 protected function getExamples() {
261 return false;
262 }
263
264 /**
265 * Returns an array of allowed parameters (keys) => default value for that parameter
266 */
267 protected function getAllowedParams() {
268 return false;
269 }
270
271 /**
272 * Returns the description string for the given parameter.
273 */
274 protected function getParamDescription() {
275 return false;
276 }
277
278 /**
279 * This method mangles parameter name based on the prefix supplied to the constructor.
280 * Override this method to change parameter name during runtime
281 */
282 public function encodeParamName($paramName) {
283 return $this->mParamPrefix . $paramName;
284 }
285
286 /**
287 * Using getAllowedParams(), makes an array of the values provided by the user,
288 * with key being the name of the variable, and value - validated value from user or default.
289 * This method can be used to generate local variables using extract().
290 */
291 public function extractRequestParams() {
292 $params = $this->getAllowedParams();
293 $results = array ();
294
295 foreach ($params as $paramName => $paramSettings)
296 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
297
298 return $results;
299 }
300
301 /**
302 * Get a value for the given parameter
303 */
304 protected function getParameter($paramName) {
305 $params = $this->getAllowedParams();
306 $paramSettings = $params[$paramName];
307 return $this->getParameterFromSettings($paramName, $paramSettings);
308 }
309
310 public static function getValidNamespaces() {
311 static $mValidNamespaces = null;
312 if (is_null($mValidNamespaces)) {
313
314 global $wgContLang;
315 $mValidNamespaces = array ();
316 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
317 if ($ns >= 0)
318 $mValidNamespaces[] = $ns;
319 }
320 }
321 return $mValidNamespaces;
322 }
323
324 /**
325 * Using the settings determine the value for the given parameter
326 * @param $paramName String: parameter name
327 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
328 */
329 protected function getParameterFromSettings($paramName, $paramSettings) {
330
331 // Some classes may decide to change parameter names
332 $paramName = $this->encodeParamName($paramName);
333
334 if (!is_array($paramSettings)) {
335 $default = $paramSettings;
336 $multi = false;
337 $type = gettype($paramSettings);
338 } else {
339 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
340 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
341 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
342
343 // When type is not given, and no choices, the type is the same as $default
344 if (!isset ($type)) {
345 if (isset ($default))
346 $type = gettype($default);
347 else
348 $type = 'NULL'; // allow everything
349 }
350 }
351
352 if ($type == 'boolean') {
353 if (isset ($default) && $default !== false) {
354 // Having a default value of anything other than 'false' is pointless
355 ApiBase :: dieDebug(__METHOD__, "Boolean param $paramName's default is set to '$default'");
356 }
357
358 $value = $this->getMain()->getRequest()->getCheck($paramName);
359 } else {
360 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
361
362 if (isset ($value) && $type == 'namespace')
363 $type = ApiBase :: getValidNamespaces();
364 }
365
366 if (isset ($value) && ($multi || is_array($type)))
367 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
368
369 // More validation only when choices were not given
370 // choices were validated in parseMultiValue()
371 if (isset ($value)) {
372 if (!is_array($type)) {
373 switch ($type) {
374 case 'NULL' : // nothing to do
375 break;
376 case 'string' : // nothing to do
377 break;
378 case 'integer' : // Force everything using intval() and optionally validate limits
379
380 $value = is_array($value) ? array_map('intval', $value) : intval($value);
381 $checkMin = isset ($paramSettings[self :: PARAM_MIN]);
382 $checkMax = isset ($paramSettings[self :: PARAM_MAX]);
383
384 if ($checkMin || $checkMax) {
385 $min = $checkMin ? $paramSettings[self :: PARAM_MIN] : false;
386 $max = $checkMax ? $paramSettings[self :: PARAM_MAX] : false;
387
388 $values = is_array($value) ? $value : array($value);
389 foreach ($values as $v) {
390 if ($checkMin && $v < $min)
391 $this->dieUsage("$paramName may not be less than $min (set to $v)", $paramName);
392 if ($checkMax && $v > $max)
393 $this->dieUsage("$paramName may not be over $max (set to $v)", $paramName);
394 }
395 }
396 break;
397 case 'limit' :
398 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
399 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $paramName");
400 if ($multi)
401 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
402 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
403 $value = intval($value);
404 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
405 break;
406 case 'boolean' :
407 if ($multi)
408 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
409 break;
410 case 'timestamp' :
411 if ($multi)
412 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
413 $value = wfTimestamp(TS_UNIX, $value);
414 if ($value === 0)
415 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
416 $value = wfTimestamp(TS_MW, $value);
417 break;
418 case 'user' :
419 $title = Title::makeTitleSafe( NS_USER, $value );
420 if ( is_null( $title ) )
421 $this->dieUsage("Invalid value $user for user parameter $paramName", "baduser_{$paramName}");
422 $value = $title->getText();
423 break;
424 default :
425 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
426 }
427 }
428
429 // There should never be any duplicate values in a list
430 if (is_array($value))
431 $value = array_unique($value);
432 }
433
434 return $value;
435 }
436
437 /**
438 * Return an array of values that were given in a 'a|b|c' notation,
439 * after it optionally validates them against the list allowed values.
440 *
441 * @param valueName - The name of the parameter (for error reporting)
442 * @param value - The value being parsed
443 * @param allowMultiple - Can $value contain more than one value separated by '|'?
444 * @param allowedValues - An array of values to check against. If null, all values are accepted.
445 * @return (allowMultiple ? an_array_of_values : a_single_value)
446 */
447 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
448 $valuesList = explode('|', $value);
449 if (!$allowMultiple && count($valuesList) != 1) {
450 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
451 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
452 }
453 if (is_array($allowedValues)) {
454 $unknownValues = array_diff($valuesList, $allowedValues);
455 if ($unknownValues) {
456 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
457 }
458 }
459
460 return $allowMultiple ? $valuesList : $valuesList[0];
461 }
462
463 /**
464 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
465 */
466 function validateLimit($varname, $value, $min, $max, $botMax) {
467 if ($value < $min) {
468 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
469 }
470
471 if ($this->getMain()->isBot()) {
472 if ($value > $botMax) {
473 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
474 }
475 }
476 elseif ($value > $max) {
477 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
478 }
479 }
480
481 /**
482 * Call main module's error handler
483 */
484 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
485 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
486 }
487
488 /**
489 * Internal code errors should be reported with this method
490 */
491 protected static function dieDebug($method, $message) {
492 wfDebugDieBacktrace("Internal error in $method: $message");
493 }
494
495 /**
496 * Profiling: total module execution time
497 */
498 private $mTimeIn = 0, $mModuleTime = 0;
499
500 /**
501 * Start module profiling
502 */
503 public function profileIn() {
504 if ($this->mTimeIn !== 0)
505 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
506 $this->mTimeIn = microtime(true);
507 wfProfileIn($this->getModuleProfileName());
508 }
509
510 /**
511 * End module profiling
512 */
513 public function profileOut() {
514 if ($this->mTimeIn === 0)
515 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
516 if ($this->mDBTimeIn !== 0)
517 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
518
519 $this->mModuleTime += microtime(true) - $this->mTimeIn;
520 $this->mTimeIn = 0;
521 wfProfileOut($this->getModuleProfileName());
522 }
523
524 /**
525 * When modules crash, sometimes it is needed to do a profileOut() regardless
526 * of the profiling state the module was in. This method does such cleanup.
527 */
528 public function safeProfileOut() {
529 if ($this->mTimeIn !== 0) {
530 if ($this->mDBTimeIn !== 0)
531 $this->profileDBOut();
532 $this->profileOut();
533 }
534 }
535
536 /**
537 * Total time the module was executed
538 */
539 public function getProfileTime() {
540 if ($this->mTimeIn !== 0)
541 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
542 return $this->mModuleTime;
543 }
544
545 /**
546 * Profiling: database execution time
547 */
548 private $mDBTimeIn = 0, $mDBTime = 0;
549
550 /**
551 * Start module profiling
552 */
553 public function profileDBIn() {
554 if ($this->mTimeIn === 0)
555 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
556 if ($this->mDBTimeIn !== 0)
557 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
558 $this->mDBTimeIn = microtime(true);
559 wfProfileIn($this->getModuleProfileName(true));
560 }
561
562 /**
563 * End database profiling
564 */
565 public function profileDBOut() {
566 if ($this->mTimeIn === 0)
567 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
568 if ($this->mDBTimeIn === 0)
569 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
570
571 $time = microtime(true) - $this->mDBTimeIn;
572 $this->mDBTimeIn = 0;
573
574 $this->mDBTime += $time;
575 $this->getMain()->mDBTime += $time;
576 wfProfileOut($this->getModuleProfileName(true));
577 }
578
579 /**
580 * Total time the module used the database
581 */
582 public function getProfileDBTime() {
583 if ($this->mDBTimeIn !== 0)
584 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
585 return $this->mDBTime;
586 }
587
588 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
589 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
590 var_export($value);
591 if ($backtrace)
592 print "\n" . wfBacktrace();
593 print "\n</pre>\n";
594 }
595
596 public abstract function getVersion();
597
598 public static function getBaseVersion() {
599 return __CLASS__ . ': $Id$';
600 }
601 }
602 ?>