-
Notifications
You must be signed in to change notification settings - Fork 8
/
axonrest.php
311 lines (267 loc) · 7.29 KB
/
axonrest.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
<?php
/**
AxonREST plugin for the PHP Fat-Free Framework
Provides REST access to an Axon model, automagically.
The contents of this file are subject to the terms of the GNU General
Public License Version 3.0. You may not use this file except in
compliance with the license. Any of the license terms and conditions
can be waived if you get permission from the copyright holder.
Copyright (c) 2010-2011 Killsaw
Steven Bredenberg <steven@killsaw.com>
@package AxonREST
@version 1.0.0
**/
//! Plugin for REST access to an Axon model.
class AxonREST extends Core {
//! Minimum framework version required to run
const F3_Minimum='1.4.0';
//! Service status messages.
const Status_Failure = 'FAILURE',
Status_Success = 'SUCCESS';
//@{
//! Locale-specific error/exception messages
const
TEXT_NeedResourceID='Please provide a resource identifier.',
TEXT_NoAccess='You do not have the priveleges to access this resource.',
TEXT_NoModelNameSet='No model name has been specified.';
//@}
//! Allows for the use of ACL or other access restrictions.
static protected $accessDelegate=false;
//! Allows for hard set object names not pulled from route vars.
static protected $objectName=null;
/**
Centralized JSON-encoded output for REST client.
@param $status string
@param $code string
@param $message string
@public
**/
static protected function reportStatus($status, $message=null, $code=null) {
echo json_encode(array(
'status'=>$status,
'code'=>$code,
'message'=>$message
));
}
/**
Get Axon model for current request.
@return AxonHelper
@param $name string
@param $where string
@public
**/
static protected function getObject($name, $where=null) {
// Scary hack. Make properties on Axon available to AxonREST
if (!in_array('AxonHelper', get_declared_classes())) {
$class = str_replace(
'class Axon',
'class AxonHelper',
str_replace(
'private ',
'public ',
file_get_contents(__DIR__."/axon.php")
)
);
eval('?>'.$class);
}
// Now load this mess.
$x = new AxonHelper($name);
if ($where !== null) {
list($pk) = each($x->keys);
if (is_numeric($where)) {
$where = sprintf("%s=%d", $pk, intval($where));
} else {
$where = sprintf("%s='%s'", $pk,
addslashes(preg_replace('/[^[:print:]]/', '', $where)));
}
$x->load($where);
}
return $x;
}
/**
Get effective object name for Axon model.
@return string
@public
**/
static public function getObjectName() {
if (!empty(self::$objectName)) {
return self::$objectName;
} elseif (F3::get('PARAMS["name"]')) {
return F3::get('PARAMS["name"]');
} else {
trigger_error(self::TEXT_NoModelNameSet);
}
}
/**
Hard-set object name for Axon model.
@param $objectName string
@public
**/
static public function setObjectName($objectName) {
self::$objectName = $objectName;
}
/**
Sets callback for access checks.
@param $delegate callable
@public
**/
static public function setAccessDelegate($delegate) {
if (is_callable($delegate)) {
self::$accessDelegate = $delegate;
}
}
/**
Check access to current object.
@return bool
@param $object string
@param $constraints string
@public
**/
static protected function hasAccess($object, $action, $object_id=null) {
if (self::$accessDelegate === false) {
return true;
} else {
$return = call_user_func(self::$accessDelegate,
$object, $action, $object_id
);
if (is_bool($return)) {
return $return;
} else {
// By default, deny, if an access
// delegate has been specified.
return false;
}
}
}
/**
View one or more records.
@public
**/
static public function get() {
$object_name = self::getObjectName();
$object_id = F3::get('PARAMS["id"]');
if (!self::hasAccess($object_name, 'view', $object_id)) {
self::reportStatus(self::Status_Failure, self::TEXT_NoAccess);
return;
}
if (!empty($object_id)) {
$object = self::getObject($object_name, $object_id);
if ($object->dry()) {
f3::http404();
} else {
echo json_encode($object->fields);
}
} else {
// It's a listing.
$object = self::getObject($object_name);
$fields = '*';
$where = null;
$group_by = (isset($_GET['group_by']))?$_GET['group_by']:null;
$order_by = (isset($_GET['order_by']))?$_GET['order_by']:null;
$limit = (isset($_GET['limit']))?$_GET['limit']:null;
$offset = (isset($_GET['offset']))?$_GET['offset']:null;
$find = array();
foreach(array_keys($object->fields) as $key) {
if (isset($_GET[$key]) && !empty($_GET[$key])) {
$value = $_GET[$key];
if (preg_match('/^([<>!]+)/', $value, $match)) {
$find[] = $key.$value;
} elseif ($value[0] == '%' || substr($value, -1) == '%') {
$find[] = $key." LIKE '".$value."'";
} else {
$find[] = sprintf("%s='%s'", $key, $value);
}
}
}
if (count($find) > 0) {
$where = join(' AND ', $find);
}
$show_rows = array();
$all_rows = $object->select($fields, $where, $group_by,
$order_by, $limit, $offset);
// Support row-level access filtering.
foreach($all_rows as $a) {
if (self::hasAccess($object_name, 'view', $a['id'])) {
$show_rows[] = $a;
}
}
echo json_encode($show_rows);
}
}
/**
Create a new record.
@public
**/
static public function put() {
$object_name = self::getObjectName();
$object = self::getObject($object_name);
if (!self::hasAccess($object_name, 'create')) {
self::reportStatus(self::Status_Failure, self::TEXT_NoAccess);
return;
}
foreach($_REQUEST as $k=>$v) {
if (array_key_exists($k, $object->fields)) {
$object->$k = $v;
}
}
if ($object->save() !== false) {
self::reportStatus(self::Status_Success, $object->id);
} else {
self::reportStatus(self::Status_Failure);
}
}
/**
Edit an existing record.
@public
**/
static public function post() {
$object_name = self::getObjectName();
$object_id = F3::get('PARAMS["id"]');
// Access check.
if (!self::hasAccess($object_name, 'edit', $object_id)) {
self::reportStatus(self::Status_Failure, self::TEXT_NoAccess);
return;
}
// Require an ID
if (empty($object_id)) {
self::reportStatus(self::Status_Failure, self::TEXT_NeedResourceID);
return;
}
$object = self::getObject($object_name, $object_id);
foreach($_POST as $k=>$v) {
if (array_key_exists($k, $object->fields)) {
$object->$k = $v;
}
}
if ($object->save() !== false) {
self::reportStatus(self::Status_Success);
} else {
self::reportStatus(self::Status_Failure);
}
}
/**
Delete object by ID.
@param $userid string
@public
**/
static public function delete() {
$object_name = self::getObjectName();
$object_id = F3::get('PARAMS["id"]');
// Access check.
if (!self::hasAccess($object_name, 'delete', $object_id)) {
self::reportStatus(self::Status_Failure, self::TEXT_NoAccess);
return;
}
// Require an ID.
if (empty($object_id)) {
self::reportStatus(self::Status_Failure, self::TEXT_NeedResourceID);
return;
}
$object = self::getObject($object_name, $object_id);
if ($object->erase()) {
self::reportStatus(self::Status_Success);
} else {
self::reportStatus(self::Status_Failure);
}
}
}