Update.
[mediawiki.git] / includes / api / ApiBase.php
blob723a6792f6e368cf614e00ebf2c6ac4dc02052e6
1 <?php
3 /*
4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
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:
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
35 * Self-documentation: code to allow api to document its own state.
37 * @addtogroup API
39 abstract class ApiBase {
41 // These constants allow modules to specify exactly how to treat incomming parameters.
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;
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
55 private $mMainModule, $mModuleName, $mParamPrefix;
57 /**
58 * Constructor
60 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
61 $this->mMainModule = $mainModule;
62 $this->mModuleName = $moduleName;
63 $this->mParamPrefix = $paramPrefix;
66 /**
67 * Executes this module
69 public abstract function execute();
71 /**
72 * Get the name of the module being executed by this instance
74 public function getModuleName() {
75 return $this->mModuleName;
78 /**
79 * Get parameter prefix (usually two letters or an empty string).
81 public function getParamPrefix() {
82 return $this->mParamPrefix;
85 /**
86 * Get the name of the module as shown in the profiler log
88 public function getModuleProfileName($db = false) {
89 if ($db)
90 return 'API:' . $this->mModuleName . '-DB';
91 else
92 return 'API:' . $this->mModuleName;
95 /**
96 * Get main module
98 public function getMain() {
99 return $this->mMainModule;
103 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
105 public function isMain() {
106 return $this === $this->mMainModule;
110 * Get result object
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();
121 * Get the result data array
123 public function & getResultData() {
124 return $this->getResult()->getData();
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.
132 public function getCustomPrinter() {
133 return null;
137 * Generates help message for this module, or false if there is no description
139 public function makeHelpMsg() {
141 static $lnPrfx = "\n ";
143 $msg = $this->getDescription();
145 if ($msg !== false) {
147 if (!is_array($msg))
148 $msg = array (
149 $msg
151 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
153 // Parameters
154 $paramsMsg = $this->makeHelpMsgParameters();
155 if ($paramsMsg !== false) {
156 $msg .= "Parameters:\n$paramsMsg";
159 // Examples
160 $examples = $this->getExamples();
161 if ($examples !== false) {
162 if (!is_array($examples))
163 $examples = array (
164 $examples
166 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
167 $msg .= implode($lnPrfx, $examples) . "\n";
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';
175 if (is_array($versions)) {
176 foreach ($versions as &$v)
177 $v = eregi_replace($pattern, $replacement, $v);
178 $versions = implode("\n ", $versions);
180 else
181 $versions = eregi_replace($pattern, $replacement, $versions);
183 $msg .= "Version:\n $versions\n";
187 return $msg;
190 public function makeHelpMsgParameters() {
191 $params = $this->getAllowedParams();
192 if ($params !== false) {
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);
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: ';
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]}";
238 $desc .= $paramPrefix . $intRangeStr;
240 break;
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";
249 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
251 return $msg;
253 } else
254 return false;
258 * Returns the description string for this module
260 protected function getDescription() {
261 return false;
265 * Returns usage examples for this module. Return null if no examples are available.
267 protected function getExamples() {
268 return false;
272 * Returns an array of allowed parameters (keys) => default value for that parameter
274 protected function getAllowedParams() {
275 return false;
279 * Returns the description string for the given parameter.
281 protected function getParamDescription() {
282 return false;
286 * This method mangles parameter name based on the prefix supplied to the constructor.
287 * Override this method to change parameter name during runtime
289 public function encodeParamName($paramName) {
290 return $this->mParamPrefix . $paramName;
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().
298 public function extractRequestParams() {
299 $params = $this->getAllowedParams();
300 $results = array ();
302 foreach ($params as $paramName => $paramSettings)
303 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
305 return $results;
309 * Get a value for the given parameter
311 protected function getParameter($paramName) {
312 $params = $this->getAllowedParams();
313 $paramSettings = $params[$paramName];
314 return $this->getParameterFromSettings($paramName, $paramSettings);
317 public static function getValidNamespaces() {
318 static $mValidNamespaces = null;
319 if (is_null($mValidNamespaces)) {
321 global $wgContLang;
322 $mValidNamespaces = array ();
323 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
324 if ($ns >= 0)
325 $mValidNamespaces[] = $ns;
328 return $mValidNamespaces;
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.
336 protected function getParameterFromSettings($paramName, $paramSettings) {
338 // Some classes may decide to change parameter names
339 $paramName = $this->encodeParamName($paramName);
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;
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
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'");
365 $value = $this->getMain()->getRequest()->getCheck($paramName);
366 } else {
367 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
369 if (isset ($value) && $type == 'namespace')
370 $type = ApiBase :: getValidNamespaces();
373 if (isset ($value) && ($multi || is_array($type)))
374 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
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
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]);
391 if ($checkMin || $checkMax) {
392 $min = $checkMin ? $paramSettings[self :: PARAM_MIN] : false;
393 $max = $checkMax ? $paramSettings[self :: PARAM_MAX] : false;
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);
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");
436 // There should never be any duplicate values in a list
437 if (is_array($value))
438 $value = array_unique($value);
441 return $value;
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.
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)
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");
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");
467 return $allowMultiple ? $valuesList : $valuesList[0];
471 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
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);
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);
483 elseif ($value > $max) {
484 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
489 * Call main module's error handler
491 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
492 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
496 * Internal code errors should be reported with this method
498 protected static function dieDebug($method, $message) {
499 wfDebugDieBacktrace("Internal error in $method: $message");
503 * Profiling: total module execution time
505 private $mTimeIn = 0, $mModuleTime = 0;
508 * Start module profiling
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());
518 * End module profiling
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()');
526 $this->mModuleTime += microtime(true) - $this->mTimeIn;
527 $this->mTimeIn = 0;
528 wfProfileOut($this->getModuleProfileName());
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.
535 public function safeProfileOut() {
536 if ($this->mTimeIn !== 0) {
537 if ($this->mDBTimeIn !== 0)
538 $this->profileDBOut();
539 $this->profileOut();
544 * Total time the module was executed
546 public function getProfileTime() {
547 if ($this->mTimeIn !== 0)
548 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
549 return $this->mModuleTime;
553 * Profiling: database execution time
555 private $mDBTimeIn = 0, $mDBTime = 0;
558 * Start module profiling
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));
570 * End database profiling
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');
578 $time = microtime(true) - $this->mDBTimeIn;
579 $this->mDBTimeIn = 0;
581 $this->mDBTime += $time;
582 $this->getMain()->mDBTime += $time;
583 wfProfileOut($this->getModuleProfileName(true));
587 * Total time the module used the database
589 public function getProfileDBTime() {
590 if ($this->mDBTimeIn !== 0)
591 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
592 return $this->mDBTime;
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";
603 public abstract function getVersion();
605 public static function getBaseVersion() {
606 return __CLASS__ . ': $Id$';