* API: All pages list
[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 $params = $this->GetAllowedParams();
96 if ($params !== false) {
97 $paramsDescription = $this->GetParamDescription();
98 $msg .= "Parameters:\n";
99 foreach (array_keys($params) as $paramName) {
100 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
101 if (is_array($desc))
102 $desc = implode("\n" . str_repeat(' ', 19), $desc);
103 $msg .= sprintf(" %-14s - %s\n", $paramName, $desc);
104 }
105 }
106
107 // Examples
108 $examples = $this->GetExamples();
109 if ($examples !== false) {
110 if (!is_array($examples))
111 $examples = array (
112 $examples
113 );
114 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
115 $msg .= implode($lnPrfx, $examples) . "\n";
116 }
117 }
118
119 return $msg;
120 }
121
122 /**
123 * Returns the description string for this module
124 */
125 protected function GetDescription() {
126 return false;
127 }
128
129 /**
130 * Returns usage examples for this module. Return null if no examples are available.
131 */
132 protected function GetExamples() {
133 return false;
134 }
135
136 /**
137 * Returns an array of allowed parameters (keys) => default value for that parameter
138 */
139 protected function GetAllowedParams() {
140 return false;
141 }
142
143 /**
144 * Returns the description string for the given parameter.
145 */
146 protected function GetParamDescription() {
147 return false;
148 }
149
150 /**
151 * Using GetAllowedParams(), makes an array of the values provided by the user,
152 * with key being the name of the variable, and value - validated value from user or default.
153 * This method can be used to generate local variables using extract().
154 */
155 public function ExtractRequestParams() {
156 global $wgRequest;
157
158 $params = $this->GetAllowedParams();
159 $results = array ();
160
161 foreach ($params as $param => $enumParams) {
162
163 if (!is_array($enumParams)) {
164 $default = $enumParams;
165 $multi = false;
166 $type = gettype($enumParams);
167 } else {
168 $default = isset ($enumParams[GN_ENUM_DFLT]) ? $enumParams[GN_ENUM_DFLT] : null;
169 $multi = isset ($enumParams[GN_ENUM_ISMULTI]) ? $enumParams[GN_ENUM_ISMULTI] : false;
170 $type = isset ($enumParams[GN_ENUM_TYPE]) ? $enumParams[GN_ENUM_TYPE] : null;
171
172 // When type is not given, and no choices, the type is the same as $default
173 if (!isset ($type)) {
174 if (isset ($default))
175 $type = gettype($default);
176 else
177 $type = 'NULL'; // allow everything
178 }
179 }
180
181 if ($type == 'boolean') {
182 if (!isset ($default))
183 $default = false;
184
185 if ($default !== false) {
186 // Having a default value of anything other than 'false' is pointless
187 $this->DieDebug("Boolean param $param's default is set to '$default'");
188 }
189 }
190
191 $value = $wgRequest->getVal($param, $default);
192
193 if (isset ($value) && ($multi || is_array($type)))
194 $value = $this->ParseMultiValue($param, $value, $multi, is_array($type) ? $type : null);
195
196 // More validation only when choices were not given
197 // choices were validated in ParseMultiValue()
198 if (!is_array ($type) && isset ($value)) {
199
200 switch ($type) {
201 case 'NULL' : // nothing to do
202 break;
203 case 'string' : // nothing to do
204 break;
205 case 'integer' : // Force everything using intval()
206 $value = is_array($value) ? array_map('intval', $value) : intval($value);
207 break;
208 case 'limit':
209 if (!isset ($enumParams[GN_ENUM_MAX1]) || !isset($enumParams[GN_ENUM_MAX2]))
210 $this->DieDebug("MAX1 or MAX2 are not defined for the limit $param");
211 if ($multi)
212 $this->DieDebug("Multi-values not supported for $param");
213 $min = isset($enumParams[GN_ENUM_MIN]) ? $enumParams[GN_ENUM_MIN] : 0;
214 $value = intval($value);
215 $this->ValidateLimit($param, $value, $min, $enumParams[GN_ENUM_MAX1], $enumParams[GN_ENUM_MAX2]);
216 break;
217 case 'boolean' :
218 if ($multi)
219 $this->DieDebug("Multi-values not supported for $param");
220 $value = isset ($value);
221 break;
222 case 'timestamp' :
223 if ($multi)
224 $this->DieDebug("Multi-values not supported for $param");
225 $value = $this->prepareTimestamp($value); // Adds quotes around timestamp
226 break;
227 default :
228 $this->DieDebug("Param $param's type is unknown - $type");
229
230 }
231 }
232
233 $results[$param] = $value;
234 }
235
236 return $results;
237 }
238
239 /**
240 * Return an array of values that were given in a "a|b|c" notation,
241 * after it optionally validates them against the list allowed values.
242 *
243 * @param valueName - The name of the parameter (for error reporting)
244 * @param value - The value being parsed
245 * @param allowMultiple - Can $value contain more than one value separated by '|'?
246 * @param allowedValues - An array of values to check against. If null, all values are accepted.
247 * @return (allowMultiple ? an_array_of_values : a_single_value)
248 */
249 protected function ParseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
250 $valuesList = explode('|', $value);
251 if (!$allowMultiple && count($valuesList) != 1) {
252 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
253 $this->DieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
254 }
255 if (is_array($allowedValues)) {
256 $unknownValues = array_diff($valuesList, $allowedValues);
257 if ($unknownValues) {
258 $this->DieUsage("Unrecognised value" . (count($unknownValues) > 1 ? "s '" : " '") . implode("', '", $unknownValues) . "' for parameter '$valueName'", "unknown_$valueName");
259 }
260 }
261
262 return $allowMultiple ? $valuesList : $valuesList[0];
263 }
264
265 /**
266 * Validate the proper format of the timestamp string (14 digits), and add quotes to it.
267 */
268 function prepareTimestamp($value) {
269 if (preg_match('/^[0-9]{14}$/', $value)) {
270 return $this->db->addQuotes($value);
271 } else {
272 $this->dieUsage('Incorrect timestamp format', 'badtimestamp');
273 }
274 }
275
276 /**
277 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
278 */
279 function ValidateLimit( $varname, $value, $min, $max, $botMax )
280 {
281 global $wgUser;
282
283 if ( $value < $min ) {
284 $this->dieUsage( "$varname may not be less than $min (set to $value)", $varname );
285 }
286
287 if( $this->GetMain()->IsBot() ) {
288 if ( $value > $botMax ) {
289 $this->dieUsage( "$varname may not be over $botMax (set to $value) for bots", $varname );
290 }
291 } else {
292 if( $value > $max ) {
293 $this->dieUsage( "$varname may not be over $max (set to $value) for users", $varname );
294 }
295 }
296 }
297
298 /**
299 * Call main module's error handler
300 */
301 public function DieUsage($description, $errorCode, $httpRespCode = 0) {
302 $this->GetMain()->MainDieUsage($description, $errorCode, $httpRespCode);
303 }
304
305 protected function DieDebug($message) {
306 wfDebugDieBacktrace("Internal error in '{get_class($this)}': $message");
307 }
308 }
309 ?>