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