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