This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
class.apiengine.php
401 lines (334 loc) · 11.8 KB
/
class.apiengine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
<?php
/**
* API engine for dispatching API requests and their corresponding methods.
*
* @package API
* @since 0.1.0
* @author Kasper Kronborg Isager <kasperisager@gmail.com>
* @copyright Copyright (c) 2013-2015 Kasper Kronborg Isager
* @license http://opensource.org/licenses/MIT MIT
* @final
*/
final class APIEngine
{
/**
* HTTP methods supported by the API
*
* If any other methods are used, the API dispatcher will throw a 405 Method
* Not Implemented exception.
*
* @since 0.1.0
* @access private
* @var array
* @static
*/
private static $supportedMethods = ["get", "post", "put", "delete", "head", "options"];
/**
* Exploded request URI
*
* @since 0.1.0
* @access private
* @var null|array
* @static
*/
private static $requestUri;
/**
* Request method
*
* @since 0.1.0
* @access private
* @var null|string
* @static
*/
private static $requestMethod;
/**
* Array of request arguments
*
* @since 0.1.0
* @access private
* @var null|array
* @static
*/
private static $requestArguments;
/**
* Array of server arguments
*
* @since 0.1.0
* @access private
* @var null|array
* @static
*/
private static $serverArguments;
/**
* Map the API request to the corrosponding controller
*
* @since 0.1.0
* @access public
* @throws Exception
* @return void
* @static
*/
public static function dispatchRequest()
{
$request = Gdn::request();
$requestUri = static::getRequestUri();
$requestMethod = static::getRequestMethod();
if (!in_array($requestMethod, static::$supportedMethods)) {
throw new Exception(t("API.Error.MethodNotAllowed"), 405);
}
if (!Gdn::session()->isValid()) {
$username = getIncomingValue("username");
$email = getIncomingValue("email");
if ($username || $email) {
APIAuth::authenticateRequest();
}
}
$resource = val(1, $requestUri);
$apiClass = ucfirst($resource) . "API";
if (!class_exists($apiClass)) {
throw new Exception(sprintf(t("API.Error.Class.Invalid"), $apiClass), 404);
}
if (!is_subclass_of($apiClass, "APIMapper")) {
throw new Exception(t("API.Error.Mapper"), 500);
}
$apiClass = new $apiClass;
$isWriteMethod = in_array($requestMethod, ["post", "put", "delete"]);
$requestArguments = ($isWriteMethod) ? static::getRequestArguments() : [];
$dispatch = static::map($resource, $apiClass, $requestUri, $requestMethod, $requestArguments);
$controller = $dispatch["controller"];
if (!$controller) {
throw new Exception(t("API.Error.Controller.Missing"), 500);
}
$inputData = array_merge($requestArguments, $dispatch["arguments"]);
if ($isWriteMethod) {
// Set the transient key since we no longer have a front-end that
// takes care of doing it for us
$inputData["TransientKey"] = Gdn::session()->transientKey();
// Authentication is always required for write-methods
$dispatch["authenticate"] = true;
// As Garden doesn"t take PUT and DELETE requests into account when
// verifying requests using IsPostBack() and IsAuthencatedPostBack(),
// we need to mask PUTs and DELETEs as POSTs.
$request->requestMethod("post");
// Add any API-specific arguments to the requests arguments
$request->setRequestArguments(Gdn_Request::INPUT_POST, $inputData);
// Set the PHP $_POST global as the result of any form data picked
// up by Garden.
$_POST = $request->post();
}
if ($dispatch["authenticate"] && !Gdn::session()->isValid()) {
throw new Exception(t("API.Error.AuthRequired"), 401);
}
$application = $dispatch["application"];
if ($application) {
Gdn_Autoloader::attachApplication($application);
}
$method = $dispatch["method"];
$arguments = $dispatch["arguments"];
Gdn::request()->withControllerMethod($controller, $method, $arguments);
}
/**
* Map a resource to its corresponding controller
*
* @since 0.1.0
* @access public
* @param array $path URI path array
* @param string $method HTTP method
* @param array $data Request arguments
* @return array Dispatch instruction for Garden.
* @static
*/
public static function map($resource, $class, $path, $method, $data)
{
$router = new AltoRouter();
$router->setBasePath("/api");
$endpoints = $class->endpoints($data);
if ($method == "options") {
$supports = strtoupper(implode(", ", $class::supports()));
$documentation = [];
foreach ($endpoints as $method => $endpoints) {
foreach ($endpoints as $endpoint => $data) {
$documentation[$method][] = paths($resource, $endpoint);
}
}
$documentation = base64_encode(json_encode($documentation));
return [
"application" => "API",
"controller" => "API",
"method" => "options",
"arguments" => [$supports, $documentation],
"authenticate" => false
];
} else {
// Register all endpoints in the router
foreach ($endpoints as $method => $endpoints) {
foreach ($endpoints as $endpoint => $data) {
$endpoint = "/" . $resource . rtrim($endpoint, "/");
// Check if route is enabled
if (!c("API.DisabledRoutes." . strtoupper($method) . "." . $endpoint)) {
$router->map($method, $endpoint, $data);
}
}
}
$match = $router->match("/" . rtrim(join("/", $path), "/"));
if (!$match) {
throw new Exception(t("API.Error.MethodNotAllowed"), 405);
}
$target = val("target", $match);
$arguments = array_merge(
val("params", $match, []),
val("arguments", $target, [])
);
return [
"application" => val("application", $target, false),
"controller" => val("controller", $target),
"method" => val("method", $target, "index"),
"authenticate" => val("authenticate", $target),
"arguments" => $arguments
];
}
}
/**
* Set the header format based on the Request object"s HTTP_ACCEPT header
*
* @since 1.0.0
* @access public
* @return void
* @static
*/
public static function setRequestHeaders()
{
// CORS support (experimental)
if (c("API.AllowCORS")) {
$headers = "Origin, X-Requested-With, Content-Type, Accept";
header("Access-Control-Allow-Origin: *", true);
header("Access-Control-Allow-Headers: " . $headers, true);
}
// Allow enabling JSONP using API.AllowJSONP
if (c("API.AllowJSONP")) {
saveToConfig("Garden.AllowJSONP", true, false);
}
$request = Gdn::request();
switch (static::getRequestMethod()) {
// If HEAD or DELETE request, only deliver status
case "head":
case "delete":
$request->withDeliveryType(DELIVERY_TYPE_BOOL);
break;
// Otherwise, only deliver the actual data
default:
$request->withDeliveryType(DELIVERY_TYPE_DATA);
}
$type = static::getServerArguments("HTTP_ACCEPT");
// Change response format depending on HTTP_ACCEPT
switch ($type) {
case "text/xml":
case "application/xml":
$request->withDeliveryMethod(DELIVERY_METHOD_XML);
break;
case "application/json":
case "application/javascript":
$request->withDeliveryMethod(DELIVERY_METHOD_JSON);
break;
default:
throw new Exception(sprintf(t("API.Error.ContentType"), $type), 400);
}
}
/**
* Get the full Request URI path array
*
* I.e. "/foo/bar" would result in the following array: ["foo", "bar"]
*
* @since 0.1.0
* @access public
* @return array The full URI path array
* @static
*/
public static function getRequestUri()
{
if (static::$requestUri === null) {
$uri = Gdn::request()->requestUri();
static::$requestUri = preg_split("/\\//", strtolower($uri), -1, PREG_SPLIT_NO_EMPTY);
}
return static::$requestUri;
}
/**
* Get the Request method
*
* @since 0.1.0
* @access public
* @return string The Request method
* @static
*/
public static function getRequestMethod()
{
if (static::$requestMethod === null) {
$method = Gdn::request()->requestMethod();
static::$requestMethod = strtolower($method);
}
return static::$requestMethod;
}
/**
* Get and parse any request input
*
* @todo Add optional support for form-data when doing POSTs and this is
* required in the case of binary uploads
*
* @since 0.1.0
* @access public
* @return array The arguments sent along with the request
* @static
*/
public static function getRequestArguments()
{
if (static::$requestArguments === null) {
// Read the PHP input buffer. This can only be done ONCE, so we need
// to make sure that we store the data
$data = file_get_contents("php://input");
if (empty($data)) {
return static::$requestArguments = [];
}
// Get the content type of the input
$type = static::getServerArguments("CONTENT_TYPE");
switch ($type) {
case "text/xml":
case "application/xml":
$XML = (array) simplexml_load_string($data);
$data = json_decode(json_encode($XML), true);
break;
case "application/json":
case "application/javascript":
$data = json_decode($data, true);
break;
default:
throw new Exception(sprintf(t("API.Error.ContentType"), $type), 400);
}
static::$requestArguments = $data;
}
return static::$requestArguments;
}
/**
* Convenience method for accessing server arguments
*
* Returns either the full list of server arguments ($_SERVER) or the value
* of a specific key if one is passed.
*
* @since 0.1.0
* @access public
* @param bool|string $key The specific key to search for
* @return array|mixed Full array of server arguments or specific value
* @static
*/
public static function getServerArguments($key = false)
{
$request = Gdn::request();
$server = Gdn_Request::INPUT_SERVER;
if (static::$serverArguments === null) {
static::$serverArguments = $request->getRequestArguments($server);
}
$arguments = static::$serverArguments;
// If a key was specified, return the value of that key. Otherwise
// return the entire array of server arguments.
return ($key) ? strtolower(val($key, $arguments)) : $arguments;
}
}