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