If 'tables' is a string that starts with a space, treat it as user-enforced FROM...
[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 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
154 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
155
156 if (is_array($versions)) {
157 foreach ($versions as &$v)
158 $v = eregi_replace($pattern, $replacement, $v);
159 $versions = implode("\n ", $versions);
160 }
161 else
162 $versions = eregi_replace($pattern, $replacement, $versions);
163
164 $msg .= "Version:\n $versions\n";
165 }
166 }
167
168 return $msg;
169 }
170
171 public function makeHelpMsgParameters() {
172 $params = $this->getAllowedParams();
173 if ($params !== false) {
174
175 $paramsDescription = $this->getParamDescription();
176 $msg = '';
177 $paramPrefix = "\n" . str_repeat(' ', 19);
178 foreach ($params as $paramName => $paramSettings) {
179 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
180 if (is_array($desc))
181 $desc = implode($paramPrefix, $desc);
182
183 @ $type = $paramSettings[self :: PARAM_TYPE];
184 if (isset ($type)) {
185 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
186 $prompt = 'Values (separate with \'|\'): ';
187 else
188 $prompt = 'One value: ';
189
190 if (is_array($type)) {
191 $desc .= $paramPrefix . $prompt . implode(', ', $type);
192 }
193 elseif ($type == 'namespace') {
194 // Special handling because namespaces are type-limited, yet they are not given
195 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
196 }
197 }
198
199 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
200 if (!is_null($default) && $default !== false)
201 $desc .= $paramPrefix . "Default: $default";
202
203 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
204 }
205 return $msg;
206
207 } else
208 return false;
209 }
210
211 /**
212 * Returns the description string for this module
213 */
214 protected function getDescription() {
215 return false;
216 }
217
218 /**
219 * Returns usage examples for this module. Return null if no examples are available.
220 */
221 protected function getExamples() {
222 return false;
223 }
224
225 /**
226 * Returns an array of allowed parameters (keys) => default value for that parameter
227 */
228 protected function getAllowedParams() {
229 return false;
230 }
231
232 /**
233 * Returns the description string for the given parameter.
234 */
235 protected function getParamDescription() {
236 return false;
237 }
238
239 /**
240 * This method mangles parameter name based on the prefix supplied to the constructor.
241 * Override this method to change parameter name during runtime
242 */
243 public function encodeParamName($paramName) {
244 return $this->mParamPrefix . $paramName;
245 }
246
247 /**
248 * Using getAllowedParams(), makes an array of the values provided by the user,
249 * with key being the name of the variable, and value - validated value from user or default.
250 * This method can be used to generate local variables using extract().
251 */
252 public function extractRequestParams() {
253 $params = $this->getAllowedParams();
254 $results = array ();
255
256 foreach ($params as $paramName => $paramSettings)
257 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings);
258
259 return $results;
260 }
261
262 /**
263 * Get a value for the given parameter
264 */
265 protected function getParameter($paramName) {
266 $params = $this->getAllowedParams();
267 $paramSettings = $params[$paramName];
268 return $this->getParameterFromSettings($paramName, $paramSettings);
269 }
270
271 public static function getValidNamespaces() {
272 static $mValidNamespaces = null;
273 if (is_null($mValidNamespaces)) {
274
275 global $wgContLang;
276 $mValidNamespaces = array ();
277 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
278 if ($ns >= 0)
279 $mValidNamespaces[] = $ns;
280 }
281 }
282 return $mValidNamespaces;
283 }
284
285 /**
286 * Using the settings determine the value for the given parameter
287 * @param $paramName String: parameter name
288 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
289 */
290 protected function getParameterFromSettings($paramName, $paramSettings) {
291
292 // Some classes may decide to change parameter names
293 $paramName = $this->encodeParamName($paramName);
294
295 if (!is_array($paramSettings)) {
296 $default = $paramSettings;
297 $multi = false;
298 $type = gettype($paramSettings);
299 } else {
300 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
301 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
302 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
303
304 // When type is not given, and no choices, the type is the same as $default
305 if (!isset ($type)) {
306 if (isset ($default))
307 $type = gettype($default);
308 else
309 $type = 'NULL'; // allow everything
310 }
311 }
312
313 if ($type == 'boolean') {
314 if (isset ($default) && $default !== false) {
315 // Having a default value of anything other than 'false' is pointless
316 ApiBase :: dieDebug(__METHOD__, "Boolean param $paramName's default is set to '$default'");
317 }
318
319 $value = $this->getMain()->getRequest()->getCheck($paramName);
320 } else {
321 $value = $this->getMain()->getRequest()->getVal($paramName, $default);
322
323 if (isset ($value) && $type == 'namespace')
324 $type = ApiBase :: getValidNamespaces();
325 }
326
327 if (isset ($value) && ($multi || is_array($type)))
328 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
329
330 // More validation only when choices were not given
331 // choices were validated in parseMultiValue()
332 if (isset ($value)) {
333 if (!is_array($type)) {
334 switch ($type) {
335 case 'NULL' : // nothing to do
336 break;
337 case 'string' : // nothing to do
338 break;
339 case 'integer' : // Force everything using intval()
340 $value = is_array($value) ? array_map('intval', $value) : intval($value);
341 break;
342 case 'limit' :
343 if (!isset ($paramSettings[self :: PARAM_MAX1]) || !isset ($paramSettings[self :: PARAM_MAX2]))
344 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $paramName");
345 if ($multi)
346 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
347 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
348 $value = intval($value);
349 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX1], $paramSettings[self :: PARAM_MAX2]);
350 break;
351 case 'boolean' :
352 if ($multi)
353 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
354 break;
355 case 'timestamp' :
356 if ($multi)
357 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $paramName");
358 $value = wfTimestamp(TS_UNIX, $value);
359 if ($value === 0)
360 $this->dieUsage("Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}");
361 $value = wfTimestamp(TS_MW, $value);
362 break;
363 default :
364 ApiBase :: dieDebug(__METHOD__, "Param $paramName's type is unknown - $type");
365 }
366 }
367
368 // There should never be any duplicate values in a list
369 if (is_array($value))
370 $value = array_unique($value);
371 }
372
373 return $value;
374 }
375
376 /**
377 * Return an array of values that were given in a 'a|b|c' notation,
378 * after it optionally validates them against the list allowed values.
379 *
380 * @param valueName - The name of the parameter (for error reporting)
381 * @param value - The value being parsed
382 * @param allowMultiple - Can $value contain more than one value separated by '|'?
383 * @param allowedValues - An array of values to check against. If null, all values are accepted.
384 * @return (allowMultiple ? an_array_of_values : a_single_value)
385 */
386 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
387 $valuesList = explode('|', $value);
388 if (!$allowMultiple && count($valuesList) != 1) {
389 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
390 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
391 }
392 if (is_array($allowedValues)) {
393 $unknownValues = array_diff($valuesList, $allowedValues);
394 if ($unknownValues) {
395 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
396 }
397 }
398
399 return $allowMultiple ? $valuesList : $valuesList[0];
400 }
401
402 /**
403 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
404 */
405 function validateLimit($varname, $value, $min, $max, $botMax) {
406 if ($value < $min) {
407 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
408 }
409
410 if ($this->getMain()->isBot()) {
411 if ($value > $botMax) {
412 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
413 }
414 }
415 elseif ($value > $max) {
416 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
417 }
418 }
419
420 /**
421 * Call main module's error handler
422 */
423 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
424 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
425 }
426
427 /**
428 * Internal code errors should be reported with this method
429 */
430 protected static function dieDebug($method, $message) {
431 wfDebugDieBacktrace("Internal error in $method: $message");
432 }
433
434 /**
435 * Profiling: total module execution time
436 */
437 private $mTimeIn = 0, $mModuleTime = 0;
438
439 /**
440 * Start module profiling
441 */
442 public function profileIn() {
443 if ($this->mTimeIn !== 0)
444 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
445 $this->mTimeIn = microtime(true);
446 wfProfileIn($this->getModuleProfileName());
447 }
448
449 /**
450 * End module profiling
451 */
452 public function profileOut() {
453 if ($this->mTimeIn === 0)
454 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
455 if ($this->mDBTimeIn !== 0)
456 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
457
458 $this->mModuleTime += microtime(true) - $this->mTimeIn;
459 $this->mTimeIn = 0;
460 wfProfileOut($this->getModuleProfileName());
461 }
462
463 /**
464 * When modules crash, sometimes it is needed to do a profileOut() regardless
465 * of the profiling state the module was in. This method does such cleanup.
466 */
467 public function safeProfileOut() {
468 if ($this->mTimeIn !== 0) {
469 if ($this->mDBTimeIn !== 0)
470 $this->profileDBOut();
471 $this->profileOut();
472 }
473 }
474
475 /**
476 * Total time the module was executed
477 */
478 public function getProfileTime() {
479 if ($this->mTimeIn !== 0)
480 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
481 return $this->mModuleTime;
482 }
483
484 /**
485 * Profiling: database execution time
486 */
487 private $mDBTimeIn = 0, $mDBTime = 0;
488
489 /**
490 * Start module profiling
491 */
492 public function profileDBIn() {
493 if ($this->mTimeIn === 0)
494 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
495 if ($this->mDBTimeIn !== 0)
496 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
497 $this->mDBTimeIn = microtime(true);
498 wfProfileIn($this->getModuleProfileName(true));
499 }
500
501 /**
502 * End database profiling
503 */
504 public function profileDBOut() {
505 if ($this->mTimeIn === 0)
506 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
507 if ($this->mDBTimeIn === 0)
508 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
509
510 $time = microtime(true) - $this->mDBTimeIn;
511 $this->mDBTimeIn = 0;
512
513 $this->mDBTime += $time;
514 $this->getMain()->mDBTime += $time;
515 wfProfileOut($this->getModuleProfileName(true));
516 }
517
518 /**
519 * Total time the module used the database
520 */
521 public function getProfileDBTime() {
522 if ($this->mDBTimeIn !== 0)
523 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
524 return $this->mDBTime;
525 }
526
527 public abstract function getVersion();
528
529 public static function getBaseVersion() {
530 return __CLASS__ . ': $Id$';
531 }
532 }
533 ?>