API * Extra profiling for allpages * better help output
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2
3
4 /*
5 * Created on Sep 5, 2006
6 *
7 * API for MediaWiki 1.8+
8 *
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
10 *
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.
15 *
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.
20 *
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
25 */
26
27 abstract class ApiBase {
28
29 // These constants allow modules to specify exactly how to treat incomming parameters.
30
31 const PARAM_DFLT = 0;
32 const PARAM_ISMULTI = 1;
33 const PARAM_TYPE = 2;
34 const PARAM_MAX1 = 3;
35 const PARAM_MAX2 = 4;
36 const PARAM_MIN = 5;
37
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
42
43 private $mMainModule, $mModuleName, $mParamPrefix;
44
45 /**
46 * Constructor
47 */
48 public function __construct($mainModule, $moduleName, $paramPrefix = '') {
49 $this->mMainModule = $mainModule;
50 $this->mModuleName = $moduleName;
51 $this->mParamPrefix = $paramPrefix;
52 }
53
54 /**
55 * Executes this module
56 */
57 public abstract function execute();
58
59 /**
60 * Get the name of the module being executed by this instance
61 */
62 public function getModuleName() {
63 return $this->mModuleName;
64 }
65
66 /**
67 * Get the name of the module as shown in the profiler log
68 */
69 public function getModuleProfileName($db = false) {
70 if ($db)
71 return 'API:' . $this->mModuleName . '-DB';
72 else
73 return 'API:' . $this->mModuleName;
74 }
75
76 /**
77 * Get main module
78 */
79 public function getMain() {
80 return $this->mMainModule;
81 }
82
83 /**
84 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
85 */
86 public function isMain() {
87 return $this === $this->mMainModule;
88 }
89
90 /**
91 * Get result object
92 */
93 public function getResult() {
94 // Main module has getResult() method overriden
95 // Safety - avoid infinite loop:
96 if ($this->isMain())
97 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
98 return $this->getMain()->getResult();
99 }
100
101 /**
102 * Get the result data array
103 */
104 public function & getResultData() {
105 return $this->getResult()->getData();
106 }
107
108 /**
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.
112 */
113 public function getCustomPrinter() {
114 return null;
115 }
116
117 /**
118 * Generates help message for this module, or false if there is no description
119 */
120 public function makeHelpMsg() {
121
122 static $lnPrfx = "\n ";
123
124 $msg = $this->getDescription();
125
126 if ($msg !== false) {
127
128 if (!is_array($msg))
129 $msg = array (
130 $msg
131 );
132 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
133
134 // Parameters
135 $paramsMsg = $this->makeHelpMsgParameters();
136 if ($paramsMsg !== false) {
137 $msg .= "Parameters:\n$paramsMsg";
138 }
139
140 // Examples
141 $examples = $this->getExamples();
142 if ($examples !== false) {
143 if (!is_array($examples))
144 $examples = array (
145 $examples
146 );
147 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
148 $msg .= implode($lnPrfx, $examples) . "\n";
149 }
150
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";
156 }
157 }
158
159 return $msg;
160 }
161
162 public function makeHelpMsgParameters() {
163 $params = $this->getAllowedParams();
164 if ($params !== false) {
165
166 $paramsDescription = $this->getParamDescription();
167 $msg = '';
168 $paramPrefix = "\n" . str_repeat(' ', 19);
169 foreach ($params as $paramName => $paramSettings) {
170 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
171 if (is_array($desc))
172 $desc = implode($paramPrefix, $desc);
173 if (isset ($paramSettings[self :: PARAM_TYPE])) {
174 $type = $paramSettings[self :: PARAM_TYPE];
175 if (is_array($type))
176 $desc .= $paramPrefix . 'Allowed values: ' . implode(', ', $type);
177 }
178 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
179 $desc .= $paramPrefix . 'Allows multiple values separated with "|"';
180
181 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
182 if (!is_null($default) && $default !== false)
183 $desc .= $paramPrefix . "Default: $default";
184
185 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
186 }
187 return $msg;
188
189 } else
190 return false;
191 }
192
193 /**
194 * Returns the description string for this module
195 */
196 protected function getDescription() {
197 return false;
198 }
199
200 /**
201 * Returns usage examples for this module. Return null if no examples are available.
202 */
203 protected function getExamples() {
204 return false;
205 }
206
207 /**
208 * Returns an array of allowed parameters (keys) => default value for that parameter
209 */
210 protected function getAllowedParams() {
211 return false;
212 }
213
214 /**
215 * Returns the description string for the given parameter.
216 */
217 protected function getParamDescription() {
218 return false;
219 }
220
221 /**
222 * This method mangles parameter name based on the prefix supplied to the constructor.
223 * Override this method to change parameter name during runtime
224 */
225 public function encodeParamName($paramName) {
226 return $this->mParamPrefix . $paramName;
227 }
228
229 /**
230 * Using getAllowedParams(), makes an array of the values provided by the user,
231 * with key being the name of the variable, and value - validated value from user or default.
232 * This method can be used to generate local variables using extract().
233 */
234 public function extractRequestParams() {
235 $params = $this->getAllowedParams();
236 $results = array ();
237
238 foreach ($params as $paramName => $paramSettings)
239 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
240
241 return $results;
242 }
243
244 /**
245 * Get a value for the given parameter
246 */
247 protected function getParameter($paramName) {
248 $params = $this->getAllowedParams();
249 $paramSettings = $params[$paramName];
250 return $this->getParameterFromSettings($paramName, $paramSettings);
251 }
252
253 /**
254 * Using the settings determine the value for the given parameter
255 * @param $paramName String: parameter name
256 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
257 */
258 protected function getParameterFromSettings($paramName, $paramSettings) {
259
260 // Some classes may decide to change parameter names
261 $paramName = $this->encodeParamName($paramName);
262
263 if (!is_array($paramSettings)) {
264 $default = $paramSettings;
265 $multi = false;
266 $type = gettype($paramSettings);
267 } else {
268 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
269 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
270 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
271
272 // When type is not given, and no choices, the type is the same as $default
273 if (!isset ($type)) {
274 if (isset ($default))
275 $type = gettype($default);
276 else
277 $type = 'NULL'; // allow everything
278 }
279 }
280
281 if ($type == 'boolean') {
282 if (isset ($default) && $default !== false) {
283 // Having a default value of anything other than 'false' is pointless
284 ApiBase :: dieDebug(__METHOD__, "Boolean param $paramName's default is set to '$default'");
285 }
286
287 $value = $this->getMain()->getRequest()->getCheck($paramName);
288 } else {
289 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
290 }
291
292 if (isset ($value) && ($multi || is_array($type)))
293 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
294
295 // More validation only when choices were not given
296 // choices were validated in parseMultiValue()
297 if (isset ($value)) {
298 if (!is_array($type)) {
299 switch ($type) {
300 case 'NULL' : // nothing to do
301 break;
302 case 'string' : // nothing to do
303 break;
304 case 'integer' : // Force everything using intval()
305 $value = is_array($value) ? array_map('intval', $value) : intval($value);
306 break;
307 case 'limit' :
308 if (!isset ($paramSettings[self :: PARAM_MAX1]) || !isset ($paramSettings[self :: PARAM_MAX2]))
309 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $paramName");
310 if ($multi)
311 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
312 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
313 $value = intval($value);
314 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX1], $paramSettings[self :: PARAM_MAX2]);
315 break;
316 case 'boolean' :
317 if ($multi)
318 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
319 break;
320 case 'timestamp' :
321 if ($multi)
322 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
323 $value = wfTimestamp(TS_UNIX, $value);
324 if ($value === 0)
325 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
326 $value = wfTimestamp(TS_MW, $value);
327 break;
328 default :
329 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
330
331 }
332 }
333
334 // There should never be any duplicate values in a list
335 if (is_array($value))
336 $value = array_unique($value);
337 }
338
339 return $value;
340 }
341
342 /**
343 * Return an array of values that were given in a 'a|b|c' notation,
344 * after it optionally validates them against the list allowed values.
345 *
346 * @param valueName - The name of the parameter (for error reporting)
347 * @param value - The value being parsed
348 * @param allowMultiple - Can $value contain more than one value separated by '|'?
349 * @param allowedValues - An array of values to check against. If null, all values are accepted.
350 * @return (allowMultiple ? an_array_of_values : a_single_value)
351 */
352 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
353 $valuesList = explode('|', $value);
354 if (!$allowMultiple && count($valuesList) != 1) {
355 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
356 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
357 }
358 if (is_array($allowedValues)) {
359 $unknownValues = array_diff($valuesList, $allowedValues);
360 if ($unknownValues) {
361 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
362 }
363 }
364
365 return $allowMultiple ? $valuesList : $valuesList[0];
366 }
367
368 /**
369 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
370 */
371 function validateLimit($varname, $value, $min, $max, $botMax) {
372 if ($value < $min) {
373 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
374 }
375
376 if ($this->getMain()->isBot()) {
377 if ($value > $botMax) {
378 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
379 }
380 }
381 elseif ($value > $max) {
382 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
383 }
384 }
385
386 /**
387 * Call main module's error handler
388 */
389 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
390 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
391 }
392
393 /**
394 * Internal code errors should be reported with this method
395 */
396 protected static function dieDebug($method, $message) {
397 wfDebugDieBacktrace("Internal error in $method: $message");
398 }
399
400 /**
401 * Profiling: total module execution time
402 */
403 private $mTimeIn = 0, $mModuleTime = 0;
404
405 /**
406 * Start module profiling
407 */
408 public function profileIn() {
409 if ($this->mTimeIn !== 0)
410 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
411 $this->mTimeIn = microtime(true);
412 wfProfileIn($this->getModuleProfileName());
413 }
414
415 /**
416 * End module profiling
417 */
418 public function profileOut() {
419 if ($this->mTimeIn === 0)
420 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
421 if ($this->mDBTimeIn !== 0)
422 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
423
424 $this->mModuleTime += microtime(true) - $this->mTimeIn;
425 $this->mTimeIn = 0;
426 wfProfileOut($this->getModuleProfileName());
427 }
428
429 /**
430 * When modules crash, sometimes it is needed to do a profileOut() regardless
431 * of the profiling state the module was in. This method does such cleanup.
432 */
433 public function safeProfileOut() {
434 if ($this->mTimeIn !== 0) {
435 if ($this->mDBTimeIn !== 0)
436 $this->profileDBOut();
437 $this->profileOut();
438 }
439 }
440
441 /**
442 * Total time the module was executed
443 */
444 public function getProfileTime() {
445 if ($this->mTimeIn !== 0)
446 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
447 return $this->mModuleTime;
448 }
449
450 /**
451 * Profiling: database execution time
452 */
453 private $mDBTimeIn = 0, $mDBTime = 0;
454
455 /**
456 * Start module profiling
457 */
458 public function profileDBIn() {
459 if ($this->mTimeIn === 0)
460 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
461 if ($this->mDBTimeIn !== 0)
462 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
463 $this->mDBTimeIn = microtime(true);
464 wfProfileIn($this->getModuleProfileName(true));
465 }
466
467 /**
468 * End database profiling
469 */
470 public function profileDBOut() {
471 if ($this->mTimeIn === 0)
472 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
473 if ($this->mDBTimeIn === 0)
474 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
475
476 $time = microtime(true) - $this->mDBTimeIn;
477 $this->mDBTimeIn = 0;
478
479 $this->mDBTime += $time;
480 $this->getMain()->mDBTime += $time;
481 wfProfileOut($this->getModuleProfileName(true));
482 }
483
484 /**
485 * Total time the module used the database
486 */
487 public function getProfileDBTime() {
488 if ($this->mDBTimeIn !== 0)
489 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
490 return $this->mDBTime;
491 }
492
493 public abstract function getVersion();
494
495 public static function getBaseVersion() {
496 return __CLASS__ . ': $Id$';
497 }
498 }
499 ?>