* (bug 12584) Don't reset cl_timestamp when auto-updating sort key on move
[mediawiki.git] / includes / api / ApiBase.php
blobaf2a3b58e7cbfc2de888728f597ff894368a1062
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, $mModulePrefix;
57 /**
58 * Constructor
60 public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61 $this->mMainModule = $mainModule;
62 $this->mModuleName = $moduleName;
63 $this->mModulePrefix = $modulePrefix;
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 getModulePrefix() {
82 return $this->mModulePrefix;
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 * Set warning section for this module. Users should monitor this section to notice any changes in API.
130 public function setWarning($warning) {
131 $msg = array();
132 ApiResult :: setContent($msg, $warning);
133 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
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.
141 public function getCustomPrinter() {
142 return null;
146 * Generates help message for this module, or false if there is no description
148 public function makeHelpMsg() {
150 static $lnPrfx = "\n ";
152 $msg = $this->getDescription();
154 if ($msg !== false) {
156 if (!is_array($msg))
157 $msg = array (
158 $msg
160 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
162 // Parameters
163 $paramsMsg = $this->makeHelpMsgParameters();
164 if ($paramsMsg !== false) {
165 $msg .= "Parameters:\n$paramsMsg";
168 // Examples
169 $examples = $this->getExamples();
170 if ($examples !== false) {
171 if (!is_array($examples))
172 $examples = array (
173 $examples
175 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
176 $msg .= implode($lnPrfx, $examples) . "\n";
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';
184 if (is_array($versions)) {
185 foreach ($versions as &$v)
186 $v = eregi_replace($pattern, $replacement, $v);
187 $versions = implode("\n ", $versions);
189 else
190 $versions = eregi_replace($pattern, $replacement, $versions);
192 $msg .= "Version:\n $versions\n";
196 return $msg;
199 public function makeHelpMsgParameters() {
200 $params = $this->getAllowedParams();
201 if ($params !== false) {
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);
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: ';
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]}";
247 $desc .= $paramPrefix . $intRangeStr;
249 break;
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";
258 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
260 return $msg;
262 } else
263 return false;
267 * Returns the description string for this module
269 protected function getDescription() {
270 return false;
274 * Returns usage examples for this module. Return null if no examples are available.
276 protected function getExamples() {
277 return false;
281 * Returns an array of allowed parameters (keys) => default value for that parameter
283 protected function getAllowedParams() {
284 return false;
288 * Returns the description string for the given parameter.
290 protected function getParamDescription() {
291 return false;
295 * This method mangles parameter name based on the prefix supplied to the constructor.
296 * Override this method to change parameter name during runtime
298 public function encodeParamName($paramName) {
299 return $this->mModulePrefix . $paramName;
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 * limit=max will not be parsed if $parseMaxLimit is set to false; use this
307 * when the max limit is not definite, e.g. when getting revisions.
309 public function extractRequestParams($parseMaxLimit = true) {
310 $params = $this->getAllowedParams();
311 $results = array ();
313 foreach ($params as $paramName => $paramSettings)
314 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
316 return $results;
320 * Get a value for the given parameter
322 protected function getParameter($paramName) {
323 $params = $this->getAllowedParams();
324 $paramSettings = $params[$paramName];
325 return $this->getParameterFromSettings($paramName, $paramSettings);
328 public static function getValidNamespaces() {
329 static $mValidNamespaces = null;
330 if (is_null($mValidNamespaces)) {
332 global $wgContLang;
333 $mValidNamespaces = array ();
334 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
335 if ($ns >= 0)
336 $mValidNamespaces[] = $ns;
339 return $mValidNamespaces;
343 * Using the settings determine the value for the given parameter
344 * @param $paramName String: parameter name
345 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
346 * @param $parseMaxLimit Boolean: parse limit when max is given?
348 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
350 // Some classes may decide to change parameter names
351 $encParamName = $this->encodeParamName($paramName);
353 if (!is_array($paramSettings)) {
354 $default = $paramSettings;
355 $multi = false;
356 $type = gettype($paramSettings);
357 } else {
358 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
359 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
360 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
362 // When type is not given, and no choices, the type is the same as $default
363 if (!isset ($type)) {
364 if (isset ($default))
365 $type = gettype($default);
366 else
367 $type = 'NULL'; // allow everything
371 if ($type == 'boolean') {
372 if (isset ($default) && $default !== false) {
373 // Having a default value of anything other than 'false' is pointless
374 ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
377 $value = $this->getMain()->getRequest()->getCheck($encParamName);
378 } else {
379 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
381 if (isset ($value) && $type == 'namespace')
382 $type = ApiBase :: getValidNamespaces();
385 if (isset ($value) && ($multi || is_array($type)))
386 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
388 // More validation only when choices were not given
389 // choices were validated in parseMultiValue()
390 if (isset ($value)) {
391 if (!is_array($type)) {
392 switch ($type) {
393 case 'NULL' : // nothing to do
394 break;
395 case 'string' : // nothing to do
396 break;
397 case 'integer' : // Force everything using intval() and optionally validate limits
399 $value = is_array($value) ? array_map('intval', $value) : intval($value);
400 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
401 $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
403 if (!is_null($min) || !is_null($max)) {
404 $values = is_array($value) ? $value : array($value);
405 foreach ($values as $v) {
406 $this->validateLimit($paramName, $v, $min, $max);
409 break;
410 case 'limit' :
411 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
412 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
413 if ($multi)
414 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
415 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
416 if( $value == 'max' ) {
417 if( $parseMaxLimit ) {
418 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
419 $this->getResult()->addValue( 'limits', 'limit', $value );
420 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
423 else {
424 $value = intval($value);
425 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
427 break;
428 case 'boolean' :
429 if ($multi)
430 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
431 break;
432 case 'timestamp' :
433 if ($multi)
434 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
435 $value = wfTimestamp(TS_UNIX, $value);
436 if ($value === 0)
437 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
438 $value = wfTimestamp(TS_MW, $value);
439 break;
440 case 'user' :
441 $title = Title::makeTitleSafe( NS_USER, $value );
442 if ( is_null( $title ) )
443 $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
444 $value = $title->getText();
445 break;
446 default :
447 ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
451 // There should never be any duplicate values in a list
452 if (is_array($value))
453 $value = array_unique($value);
456 return $value;
460 * Return an array of values that were given in a 'a|b|c' notation,
461 * after it optionally validates them against the list allowed values.
463 * @param valueName - The name of the parameter (for error reporting)
464 * @param value - The value being parsed
465 * @param allowMultiple - Can $value contain more than one value separated by '|'?
466 * @param allowedValues - An array of values to check against. If null, all values are accepted.
467 * @return (allowMultiple ? an_array_of_values : a_single_value)
469 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
470 $valuesList = explode('|', $value);
471 if (!$allowMultiple && count($valuesList) != 1) {
472 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
473 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
475 if (is_array($allowedValues)) {
476 $unknownValues = array_diff($valuesList, $allowedValues);
477 if ($unknownValues) {
478 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
482 return $allowMultiple ? $valuesList : $valuesList[0];
486 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
488 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
489 if (!is_null($min) && $value < $min) {
490 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
493 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
494 if ($this->getMain()->isInternalMode())
495 return;
497 // Optimization: do not check user's bot status unless really needed -- skips db query
498 // assumes $botMax >= $max
499 if (!is_null($max) && $value > $max) {
500 if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
501 if ($value > $botMax) {
502 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
504 } else {
505 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
511 * Call main module's error handler
513 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
514 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
518 * Internal code errors should be reported with this method
520 protected static function dieDebug($method, $message) {
521 wfDebugDieBacktrace("Internal error in $method: $message");
525 * Indicates if API needs to check maxlag
527 public function shouldCheckMaxlag() {
528 return true;
532 * Indicates if this module requires edit mode
534 public function isEditMode() {
535 return false;
540 * Profiling: total module execution time
542 private $mTimeIn = 0, $mModuleTime = 0;
545 * Start module profiling
547 public function profileIn() {
548 if ($this->mTimeIn !== 0)
549 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
550 $this->mTimeIn = microtime(true);
551 wfProfileIn($this->getModuleProfileName());
555 * End module profiling
557 public function profileOut() {
558 if ($this->mTimeIn === 0)
559 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
560 if ($this->mDBTimeIn !== 0)
561 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
563 $this->mModuleTime += microtime(true) - $this->mTimeIn;
564 $this->mTimeIn = 0;
565 wfProfileOut($this->getModuleProfileName());
569 * When modules crash, sometimes it is needed to do a profileOut() regardless
570 * of the profiling state the module was in. This method does such cleanup.
572 public function safeProfileOut() {
573 if ($this->mTimeIn !== 0) {
574 if ($this->mDBTimeIn !== 0)
575 $this->profileDBOut();
576 $this->profileOut();
581 * Total time the module was executed
583 public function getProfileTime() {
584 if ($this->mTimeIn !== 0)
585 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
586 return $this->mModuleTime;
590 * Profiling: database execution time
592 private $mDBTimeIn = 0, $mDBTime = 0;
595 * Start module profiling
597 public function profileDBIn() {
598 if ($this->mTimeIn === 0)
599 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
600 if ($this->mDBTimeIn !== 0)
601 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
602 $this->mDBTimeIn = microtime(true);
603 wfProfileIn($this->getModuleProfileName(true));
607 * End database profiling
609 public function profileDBOut() {
610 if ($this->mTimeIn === 0)
611 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
612 if ($this->mDBTimeIn === 0)
613 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
615 $time = microtime(true) - $this->mDBTimeIn;
616 $this->mDBTimeIn = 0;
618 $this->mDBTime += $time;
619 $this->getMain()->mDBTime += $time;
620 wfProfileOut($this->getModuleProfileName(true));
624 * Total time the module used the database
626 public function getProfileDBTime() {
627 if ($this->mDBTimeIn !== 0)
628 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
629 return $this->mDBTime;
632 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
633 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
634 var_export($value);
635 if ($backtrace)
636 print "\n" . wfBacktrace();
637 print "\n</pre>\n";
640 public abstract function getVersion();
642 public static function getBaseVersion() {
643 return __CLASS__ . ': $Id$';