5 * Created on Sep 5, 2006
7 * API for MediaWiki 1.8+
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
27 abstract class ApiBase
{
29 // These constants allow modules to specify exactly how to treat incomming parameters.
32 const PARAM_ISMULTI
= 1;
38 const LIMIT_BIG1
= 500; // Fast query, user's limit
39 const LIMIT_BIG2
= 5000; // Fast query, bot's limit
40 const LIMIT_SML1
= 50; // Slow query, user's limit
41 const LIMIT_SML2
= 500; // Slow query, bot's limit
43 private $mMainModule, $mModuleName, $mParamPrefix;
48 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
49 $this->mMainModule
= $mainModule;
50 $this->mModuleName
= $moduleName;
51 $this->mParamPrefix
= $paramPrefix;
55 * Executes this module
57 public abstract function execute();
60 * Get the name of the module being executed by this instance
62 public function getModuleName() {
63 return $this->mModuleName
;
67 * Get the name of the module as shown in the profiler log
69 public function getModuleProfileName($db = false) {
71 return 'API:' . $this->mModuleName
. '-DB';
73 return 'API:' . $this->mModuleName
;
79 public function getMain() {
80 return $this->mMainModule
;
84 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
86 public function isMain() {
87 return $this === $this->mMainModule
;
93 public function getResult() {
94 // Main module has getResult() method overriden
95 // Safety - avoid infinite loop:
97 ApiBase
:: dieDebug(__METHOD__
, 'base method was called on main module. ');
98 return $this->getMain()->getResult();
102 * Get the result data array
104 public function & getResultData() {
105 return $this->getResult()->getData();
109 * If the module may only be used with a certain format module,
110 * it should override this method to return an instance of that formatter.
111 * A value of null means the default format will be used.
113 public function getCustomPrinter() {
118 * Generates help message for this module, or false if there is no description
120 public function makeHelpMsg() {
122 static $lnPrfx = "\n ";
124 $msg = $this->getDescription();
126 if ($msg !== false) {
132 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
135 $paramsMsg = $this->makeHelpMsgParameters();
136 if ($paramsMsg !== false) {
137 $msg .= "Parameters:\n$paramsMsg";
141 $examples = $this->getExamples();
142 if ($examples !== false) {
143 if (!is_array($examples))
147 $msg .= 'Example' . (count($examples) > 1 ?
's' : '') . ":\n ";
148 $msg .= implode($lnPrfx, $examples) . "\n";
151 if ($this->getMain()->getShowVersions()) {
152 $versions = $this->getVersion();
153 if (is_array($versions))
154 $versions = implode("\n ", $versions);
155 $msg .= "Version:\n $versions\n";
162 public function makeHelpMsgParameters() {
163 $params = $this->getAllowedParams();
164 if ($params !== false) {
166 $paramsDescription = $this->getParamDescription();
168 $paramPrefix = "\n" . str_repeat(' ', 19);
169 foreach ($params as $paramName => $paramSettings) {
170 $desc = isset ($paramsDescription[$paramName]) ?
$paramsDescription[$paramName] : '';
172 $desc = implode($paramPrefix, $desc);
174 @ $type = $paramSettings[self
:: PARAM_TYPE
];
176 if (isset ($paramSettings[self
:: PARAM_ISMULTI
]))
177 $prompt = 'Values (separate with \'|\'): ';
179 $prompt = 'One value: ';
181 if (is_array($type)) {
182 $desc .= $paramPrefix . $prompt . implode(', ', $type);
184 elseif ($type == 'namespace') {
185 // Special handling because namespaces are type-limited, yet they are not given
186 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase
:: getValidNamespaces());
190 $default = is_array($paramSettings) ?
(isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null) : $paramSettings;
191 if (!is_null($default) && $default !== false)
192 $desc .= $paramPrefix . "Default: $default";
194 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
203 * Returns the description string for this module
205 protected function getDescription() {
210 * Returns usage examples for this module. Return null if no examples are available.
212 protected function getExamples() {
217 * Returns an array of allowed parameters (keys) => default value for that parameter
219 protected function getAllowedParams() {
224 * Returns the description string for the given parameter.
226 protected function getParamDescription() {
231 * This method mangles parameter name based on the prefix supplied to the constructor.
232 * Override this method to change parameter name during runtime
234 public function encodeParamName($paramName) {
235 return $this->mParamPrefix
. $paramName;
239 * Using getAllowedParams(), makes an array of the values provided by the user,
240 * with key being the name of the variable, and value - validated value from user or default.
241 * This method can be used to generate local variables using extract().
243 public function extractRequestParams() {
244 $params = $this->getAllowedParams();
247 foreach ($params as $paramName => $paramSettings)
248 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
254 * Get a value for the given parameter
256 protected function getParameter($paramName) {
257 $params = $this->getAllowedParams();
258 $paramSettings = $params[$paramName];
259 return $this->getParameterFromSettings($paramName, $paramSettings);
262 public static function getValidNamespaces() {
263 static $mValidNamespaces = null;
264 if (is_null($mValidNamespaces)) {
267 $mValidNamespaces = array ();
268 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
270 $mValidNamespaces[] = $ns;
273 return $mValidNamespaces;
277 * Using the settings determine the value for the given parameter
278 * @param $paramName String: parameter name
279 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
281 protected function getParameterFromSettings($paramName, $paramSettings) {
283 // Some classes may decide to change parameter names
284 $paramName = $this->encodeParamName($paramName);
286 if (!is_array($paramSettings)) {
287 $default = $paramSettings;
289 $type = gettype($paramSettings);
291 $default = isset ($paramSettings[self
:: PARAM_DFLT
]) ?
$paramSettings[self
:: PARAM_DFLT
] : null;
292 $multi = isset ($paramSettings[self
:: PARAM_ISMULTI
]) ?
$paramSettings[self
:: PARAM_ISMULTI
] : false;
293 $type = isset ($paramSettings[self
:: PARAM_TYPE
]) ?
$paramSettings[self
:: PARAM_TYPE
] : null;
295 // When type is not given, and no choices, the type is the same as $default
296 if (!isset ($type)) {
297 if (isset ($default))
298 $type = gettype($default);
300 $type = 'NULL'; // allow everything
304 if ($type == 'boolean') {
305 if (isset ($default) && $default !== false) {
306 // Having a default value of anything other than 'false' is pointless
307 ApiBase
:: dieDebug(__METHOD__
, "Boolean param $paramName's default is set to '$default'");
310 $value = $this->getMain()->getRequest()->getCheck($paramName);
312 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
314 if (isset ($value) && $type == 'namespace')
315 $type = ApiBase
:: getValidNamespaces();
318 if (isset ($value) && ($multi ||
is_array($type)))
319 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ?
$type : null);
321 // More validation only when choices were not given
322 // choices were validated in parseMultiValue()
323 if (isset ($value)) {
324 if (!is_array($type)) {
326 case 'NULL' : // nothing to do
328 case 'string' : // nothing to do
330 case 'integer' : // Force everything using intval()
331 $value = is_array($value) ?
array_map('intval', $value) : intval($value);
334 if (!isset ($paramSettings[self
:: PARAM_MAX1
]) ||
!isset ($paramSettings[self
:: PARAM_MAX2
]))
335 ApiBase
:: dieDebug(__METHOD__
, "MAX1 or MAX2 are not defined for the limit $paramName");
337 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
338 $min = isset ($paramSettings[self
:: PARAM_MIN
]) ?
$paramSettings[self
:: PARAM_MIN
] : 0;
339 $value = intval($value);
340 $this->validateLimit($paramName, $value, $min, $paramSettings[self
:: PARAM_MAX1
], $paramSettings[self
:: PARAM_MAX2
]);
344 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
348 ApiBase
:: dieDebug(__METHOD__
, "Multi-values not supported for $paramName");
349 $value = wfTimestamp(TS_UNIX
, $value);
351 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
352 $value = wfTimestamp(TS_MW
, $value);
355 ApiBase
:: dieDebug(__METHOD__
, "Param $paramName's type is unknown - $type");
359 // There should never be any duplicate values in a list
360 if (is_array($value))
361 $value = array_unique($value);
368 * Return an array of values that were given in a 'a|b|c' notation,
369 * after it optionally validates them against the list allowed values.
371 * @param valueName - The name of the parameter (for error reporting)
372 * @param value - The value being parsed
373 * @param allowMultiple - Can $value contain more than one value separated by '|'?
374 * @param allowedValues - An array of values to check against. If null, all values are accepted.
375 * @return (allowMultiple ? an_array_of_values : a_single_value)
377 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
378 $valuesList = explode('|', $value);
379 if (!$allowMultiple && count($valuesList) != 1) {
380 $possibleValues = is_array($allowedValues) ?
"of '" . implode("', '", $allowedValues) . "'" : '';
381 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
383 if (is_array($allowedValues)) {
384 $unknownValues = array_diff($valuesList, $allowedValues);
385 if ($unknownValues) {
386 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ?
"s" : "") . " for parameter '$valueName'", "unknown_$valueName");
390 return $allowMultiple ?
$valuesList : $valuesList[0];
394 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
396 function validateLimit($varname, $value, $min, $max, $botMax) {
398 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
401 if ($this->getMain()->isBot()) {
402 if ($value > $botMax) {
403 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
406 elseif ($value > $max) {
407 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
412 * Call main module's error handler
414 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
415 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
419 * Internal code errors should be reported with this method
421 protected static function dieDebug($method, $message) {
422 wfDebugDieBacktrace("Internal error in $method: $message");
426 * Profiling: total module execution time
428 private $mTimeIn = 0, $mModuleTime = 0;
431 * Start module profiling
433 public function profileIn() {
434 if ($this->mTimeIn
!== 0)
435 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileOut()');
436 $this->mTimeIn
= microtime(true);
437 wfProfileIn($this->getModuleProfileName());
441 * End module profiling
443 public function profileOut() {
444 if ($this->mTimeIn
=== 0)
445 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileIn() first');
446 if ($this->mDBTimeIn
!== 0)
447 ApiBase
:: dieDebug(__METHOD__
, 'must be called after database profiling is done with profileDBOut()');
449 $this->mModuleTime +
= microtime(true) - $this->mTimeIn
;
451 wfProfileOut($this->getModuleProfileName());
455 * When modules crash, sometimes it is needed to do a profileOut() regardless
456 * of the profiling state the module was in. This method does such cleanup.
458 public function safeProfileOut() {
459 if ($this->mTimeIn
!== 0) {
460 if ($this->mDBTimeIn
!== 0)
461 $this->profileDBOut();
467 * Total time the module was executed
469 public function getProfileTime() {
470 if ($this->mTimeIn
!== 0)
471 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileOut() first');
472 return $this->mModuleTime
;
476 * Profiling: database execution time
478 private $mDBTimeIn = 0, $mDBTime = 0;
481 * Start module profiling
483 public function profileDBIn() {
484 if ($this->mTimeIn
=== 0)
485 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
486 if ($this->mDBTimeIn
!== 0)
487 ApiBase
:: dieDebug(__METHOD__
, 'called twice without calling profileDBOut()');
488 $this->mDBTimeIn
= microtime(true);
489 wfProfileIn($this->getModuleProfileName(true));
493 * End database profiling
495 public function profileDBOut() {
496 if ($this->mTimeIn
=== 0)
497 ApiBase
:: dieDebug(__METHOD__
, 'must be called while profiling the entire module with profileIn()');
498 if ($this->mDBTimeIn
=== 0)
499 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBIn() first');
501 $time = microtime(true) - $this->mDBTimeIn
;
502 $this->mDBTimeIn
= 0;
504 $this->mDBTime +
= $time;
505 $this->getMain()->mDBTime +
= $time;
506 wfProfileOut($this->getModuleProfileName(true));
510 * Total time the module used the database
512 public function getProfileDBTime() {
513 if ($this->mDBTimeIn
!== 0)
514 ApiBase
:: dieDebug(__METHOD__
, 'called without calling profileDBOut() first');
515 return $this->mDBTime
;
518 public abstract function getVersion();
520 public static function getBaseVersion() {
521 return __CLASS__
. ': $Id$';