c3ce8e511f1419aad89ade636fefc1acf40b7cb8
[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 // Multi-valued enums, limit the values user can supply for the parameter
28 define('GN_ENUM_DFLT', 'dflt');
29 define('GN_ENUM_ISMULTI', 'multi');
30 define('GN_ENUM_TYPE', 'type');
31 define('GN_ENUM_MAX1', 'max1');
32 define('GN_ENUM_MAX2', 'max2');
33 define('GN_ENUM_MIN', 'min');
34
35 abstract class ApiBase {
36
37 private $mMainModule;
38
39 /**
40 * Constructor
41 */
42 public function __construct($mainModule) {
43 $this->mMainModule = $mainModule;
44 }
45
46 /**
47 * Executes this module
48 */
49 abstract function execute();
50
51 /**
52 * Get main module
53 */
54 public function getMain() {
55 return $this->mMainModule;
56 }
57
58 /**
59 * If this module's $this is the same as $this->mMainModule, its the root, otherwise no
60 */
61 public function isMain() {
62 return $this === $this->mMainModule;
63 }
64
65 /**
66 * Get result object
67 */
68 public function getResult() {
69 // Main module has getResult() method overriden
70 // Safety - avoid infinite loop:
71 if ($this->isMain())
72 $this->dieDebug(__METHOD__ .
73 ' base method was called on main module. ');
74 return $this->getMain()->getResult();
75 }
76
77 /**
78 * Generates help message for this module, or false if there is no description
79 */
80 public function makeHelpMsg() {
81
82 static $lnPrfx = "\n ";
83
84 $msg = $this->getDescription();
85
86 if ($msg !== false) {
87
88 if (!is_array($msg))
89 $msg = array (
90 $msg
91 );
92 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
93
94 // Parameters
95 $paramsMsg = $this->makeHelpMsgParameters();
96 if ($paramsMsg !== false) {
97 $msg .= "Parameters:\n$paramsMsg";
98 }
99
100 // Examples
101 $examples = $this->getExamples();
102 if ($examples !== false) {
103 if (!is_array($examples))
104 $examples = array (
105 $examples
106 );
107 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
108 $msg .= implode($lnPrfx, $examples) . "\n";
109 }
110 }
111
112 return $msg;
113 }
114
115 public function makeHelpMsgParameters() {
116 $params = $this->getAllowedParams();
117 if ($params !== false) {
118
119 $paramsDescription = $this->getParamDescription();
120 $msg = '';
121 foreach (array_keys($params) as $paramName) {
122 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
123 if (is_array($desc))
124 $desc = implode("\n" . str_repeat(' ', 19), $desc);
125 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
126 }
127 return $msg;
128
129 }
130 else
131 return false;
132 }
133
134 /**
135 * Returns the description string for this module
136 */
137 protected function getDescription() {
138 return false;
139 }
140
141 /**
142 * Returns usage examples for this module. Return null if no examples are available.
143 */
144 protected function getExamples() {
145 return false;
146 }
147
148 /**
149 * Returns an array of allowed parameters (keys) => default value for that parameter
150 */
151 protected function getAllowedParams() {
152 return false;
153 }
154
155 /**
156 * Returns the description string for the given parameter.
157 */
158 protected function getParamDescription() {
159 return false;
160 }
161
162 /**
163 * Using getAllowedParams(), makes an array of the values provided by the user,
164 * with key being the name of the variable, and value - validated value from user or default.
165 * This method can be used to generate local variables using extract().
166 */
167 public function extractRequestParams() {
168 $params = $this->getAllowedParams();
169 $results = array ();
170
171 foreach ($params as $paramName => $paramSettings)
172 $results[$paramName] = $this->getParameter($paramName, $paramSettings);
173
174 return $results;
175 }
176
177 public function getParameter($paramName, $paramSettings){
178 global $wgRequest;
179
180 if (!is_array($paramSettings)) {
181 $default = $paramSettings;
182 $multi = false;
183 $type = gettype($paramSettings);
184 } else {
185 $default = isset ($paramSettings[GN_ENUM_DFLT]) ? $paramSettings[GN_ENUM_DFLT] : null;
186 $multi = isset ($paramSettings[GN_ENUM_ISMULTI]) ? $paramSettings[GN_ENUM_ISMULTI] : false;
187 $type = isset ($paramSettings[GN_ENUM_TYPE]) ? $paramSettings[GN_ENUM_TYPE] : null;
188
189 // When type is not given, and no choices, the type is the same as $default
190 if (!isset ($type)) {
191 if (isset ($default))
192 $type = gettype($default);
193 else
194 $type = 'NULL'; // allow everything
195 }
196 }
197
198 if ($type == 'boolean') {
199 if (isset ($default) && $default !== false) {
200 // Having a default value of anything other than 'false' is pointless
201 $this->dieDebug("Boolean param $paramName's default is set to '$default'");
202 }
203
204 $value = $wgRequest->getCheck($paramName);
205 } else
206 $value = $wgRequest->getVal($paramName, $default);
207
208 if (isset ($value) && ($multi || is_array($type)))
209 $value = $this->parseMultiValue($paramName, $value, $multi, is_array($type) ? $type : null);
210
211 // More validation only when choices were not given
212 // choices were validated in parseMultiValue()
213 if (!is_array($type) && isset ($value)) {
214
215 switch ($type) {
216 case 'NULL' : // nothing to do
217 break;
218 case 'string' : // nothing to do
219 break;
220 case 'integer' : // Force everything using intval()
221 $value = is_array($value) ? array_map('intval', $value) : intval($value);
222 break;
223 case 'limit' :
224 if (!isset ($paramSettings[GN_ENUM_MAX1]) || !isset ($paramSettings[GN_ENUM_MAX2]))
225 $this->dieDebug("MAX1 or MAX2 are not defined for the limit $paramName");
226 if ($multi)
227 $this->dieDebug("Multi-values not supported for $paramName");
228 $min = isset ($paramSettings[GN_ENUM_MIN]) ? $paramSettings[GN_ENUM_MIN] : 0;
229 $value = intval($value);
230 $this->validateLimit($paramName, $value, $min, $paramSettings[GN_ENUM_MAX1], $paramSettings[GN_ENUM_MAX2]);
231 break;
232 case 'boolean' :
233 if ($multi)
234 $this->dieDebug("Multi-values not supported for $paramName");
235 break;
236 case 'timestamp' :
237 if ($multi)
238 $this->dieDebug("Multi-values not supported for $paramName");
239 $value = $this->prepareTimestamp($value); // Adds quotes around timestamp
240 break;
241 default :
242 $this->dieDebug("Param $paramName's type is unknown - $type");
243
244 }
245 }
246
247 return $value;
248 }
249
250 /**
251 * Return an array of values that were given in a "a|b|c" notation,
252 * after it optionally validates them against the list allowed values.
253 *
254 * @param valueName - The name of the parameter (for error reporting)
255 * @param value - The value being parsed
256 * @param allowMultiple - Can $value contain more than one value separated by '|'?
257 * @param allowedValues - An array of values to check against. If null, all values are accepted.
258 * @return (allowMultiple ? an_array_of_values : a_single_value)
259 */
260 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
261 $valuesList = explode('|', $value);
262 if (!$allowMultiple && count($valuesList) != 1) {
263 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
264 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
265 }
266 if (is_array($allowedValues)) {
267 $unknownValues = array_diff($valuesList, $allowedValues);
268 if ($unknownValues) {
269 $this->dieUsage("Unrecognised value" . (count($unknownValues) > 1 ? "s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
270 }
271 }
272
273 return $allowMultiple ? $valuesList : $valuesList[0];
274 }
275
276 /**
277 * Validate the proper format of the timestamp string (14 digits), and add quotes to it.
278 */
279 function prepareTimestamp($value) {
280 if (preg_match('/^[0-9]{14}$/', $value)) {
281 return $this->db->addQuotes($value);
282 } else {
283 $this->dieUsage('Incorrect timestamp format', 'badtimestamp');
284 }
285 }
286
287 /**
288 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
289 */
290 function validateLimit($varname, $value, $min, $max, $botMax) {
291 global $wgUser;
292
293 if ($value < $min) {
294 $this->dieUsage("$varname may not be less than $min (set to $value)", $varname);
295 }
296
297 if ($this->getMain()->isBot()) {
298 if ($value > $botMax) {
299 $this->dieUsage("$varname may not be over $botMax (set to $value) for bots", $varname);
300 }
301 } else {
302 if ($value > $max) {
303 $this->dieUsage("$varname may not be over $max (set to $value) for users", $varname);
304 }
305 }
306 }
307
308 /**
309 * Call main module's error handler
310 */
311 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
312 $this->getMain()->mainDieUsage($description, $errorCode, $httpRespCode);
313 }
314
315 /**
316 * Internal code errors should be reported with this method
317 */
318 protected function dieDebug($message) {
319 wfDebugDieBacktrace("Internal error in '{get_class($this)}': $message");
320 }
321
322 /**
323 * Profiling: total module execution time
324 */
325 private $mTimeIn = 0, $mModuleTime = 0;
326
327 /**
328 * Start module profiling
329 */
330 public function profileIn()
331 {
332 if ($this->mTimeIn !== 0)
333 $this->dieDebug(__FUNCTION__ . ' called twice without calling profileOut()');
334 $this->mTimeIn = microtime(true);
335 }
336
337 /**
338 * End module profiling
339 */
340 public function profileOut()
341 {
342 if ($this->mTimeIn === 0)
343 $this->dieDebug(__FUNCTION__ . ' called without calling profileIn() first');
344 if ($this->mDBTimeIn !== 0)
345 $this->dieDebug(__FUNCTION__ . ' must be called after database profiling is done with profileDBOut()');
346
347 $this->mModuleTime += microtime(true) - $this->mTimeIn;
348 $this->mTimeIn = 0;
349 }
350
351 /**
352 * Total time the module was executed
353 */
354 public function getProfileTime()
355 {
356 if ($this->mTimeIn !== 0)
357 $this->dieDebug(__FUNCTION__ . ' called without calling profileOut() first');
358 return $this->mModuleTime;
359 }
360
361 /**
362 * Profiling: database execution time
363 */
364 private $mDBTimeIn = 0, $mDBTime = 0;
365
366 /**
367 * Start module profiling
368 */
369 public function profileDBIn()
370 {
371 if ($this->mTimeIn === 0)
372 $this->dieDebug(__FUNCTION__ . ' must be called while profiling the entire module with profileIn()');
373 if ($this->mDBTimeIn !== 0)
374 $this->dieDebug(__FUNCTION__ . ' called twice without calling profileDBOut()');
375 $this->mDBTimeIn = microtime(true);
376 }
377
378 /**
379 * End database profiling
380 */
381 public function profileDBOut()
382 {
383 if ($this->mTimeIn === 0)
384 $this->dieDebug(__FUNCTION__ . ' must be called while profiling the entire module with profileIn()');
385 if ($this->mDBTimeIn === 0)
386 $this->dieDebug(__FUNCTION__ . ' called without calling profileDBIn() first');
387
388 $time = microtime(true) - $this->mDBTimeIn;
389 $this->mDBTimeIn = 0;
390
391 $this->mDBTime += $time;
392 $this->getMain()->mDBTime += $time;
393 }
394
395 /**
396 * Total time the module used the database
397 */
398 public function getProfileDBTime()
399 {
400 if ($this->mDBTimeIn !== 0)
401 $this->dieDebug(__FUNCTION__ . ' called without calling profileDBOut() first');
402 return $this->mDBTime;
403 }
404 }
405 ?>