-
Notifications
You must be signed in to change notification settings - Fork 11
/
json-rpc.php
288 lines (265 loc) · 9.53 KB
/
json-rpc.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
<?php
/*
JSON-RPC Server implemenation
Copyright (C) 2009 Jakub Jankiewicz <http://jcubic.pl>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
USAGE: create one class with public methods and call handle_json_rpc function
with instance of this class
<?php
require('json_rpc.php');
class Server {
public function test($message) {
return "you send " . $message;
}
}
handle_json_rpc(new Server());
?>
you can provide documentations for methods
by adding static field:
class Server {
...
public static $test_documentation = "doc string";
}
*/
// ----------------------------------------------------------------------------
set_error_handler('error_handler');
ini_set('display_errors', 1);
ini_set('track_errors', 1);
ob_start();
function error_handler($err, $message, $file, $line) {
global $stop;
$stop = true;
$content = explode("\n", file_get_contents($file));
header('Content-Type: application/json');
$id = extract_id(); // don't need to parse
$error = array(
"code" => 100,
"message" => "Server error",
"error" => array(
"name" => "PHPErorr",
"code" => $err,
"message" => $message,
"file" => $file,
"at" => $line,
"line" => $content[$line-1]));
ob_end_clean();
echo response(null, $id, $error);
exit();
}
// ----------------------------------------------------------------------------
class JsonRpcExeption extends Exception {
function __construct($code, $message) {
$this->code = $code;
Exception::__construct($message);
}
function code() {
return $this->code;
}
}
// ----------------------------------------------------------------------------
function json_error() {
switch (json_last_error()) {
case JSON_ERROR_NONE:
return 'No error has occurred';
case JSON_ERROR_DEPTH:
return 'The maximum stack depth has been exceeded';
case JSON_ERROR_CTRL_CHAR:
return 'Control character error, possibly incorrectly encoded';
case JSON_ERROR_SYNTAX:
return 'Syntax error';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
}
}
// ----------------------------------------------------------------------------
function get_raw_post_data() {
if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
return $GLOBALS['HTTP_RAW_POST_DATA'];
} else {
return file_get_contents('php://input');
}
}
// ----------------------------------------------------------------------------
// check if object has field
function has_field($object, $field) {
//return in_array($field, array_keys(get_object_vars($object)));
return array_key_exists($field, get_object_vars($object));
}
// ----------------------------------------------------------------------------
// return object field if exist otherwise return default value
function get_field($object, $field, $default) {
$array = get_object_vars($object);
if (isset($array[$field])) {
return $array[$field];
} else {
return $default;
}
}
// ----------------------------------------------------------------------------
//create json-rpc response
function response($result, $id, $error) {
if ($error) {
$error['name'] = 'JSONRPCError';
}
return json_encode(array("jsonrpc" => "2.0",
'result' => $result,
'id' => $id,
'error'=> $error));
}
// ----------------------------------------------------------------------------
// try to extract id from broken json
function extract_id() {
$regex = '/[\'"]id[\'"] *: *([0-9]*)/';
$raw_data = get_raw_post_data();
if (preg_match($regex, $raw_data, $m)) {
return $m[1];
} else {
return null;
}
}
// ----------------------------------------------------------------------------
function currentURL() {
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
// ----------------------------------------------------------------------------
function service_description($object) {
$class_name = get_class($object);
$methods = get_class_methods($class_name);
$service = array("sdversion" => "1.0",
"name" => "DemoService",
"address" => currentURL(),
"id" => "urn:md5:" . md5(currentURL()));
$static = get_class_vars($class_name);
foreach ($methods as $method_name) {
$proc = array("name" => $method_name);
$method = new ReflectionMethod($class_name, $method_name);
$params = array();
foreach ($method->getParameters() as $param) {
$params[] = $param->name;
}
$proc['params'] = $params;
$help_str_name = $method_name . "_documentation";
if (array_key_exists($help_str_name, $static)) {
$proc['help'] = $static[$help_str_name];
}
$service['procs'][] = $proc;
}
return $service;
}
// ----------------------------------------------------------------------------
function get_json_request() {
$request = get_raw_post_data();
if ($request == "") {
throw new JsonRpcExeption(101, "Parse Error: no data");
}
$encoding = mb_detect_encoding($request, 'auto');
//convert to unicode
if ($encoding != 'UTF-8') {
$request = iconv($encoding, 'UTF-8', $request);
}
$request = json_decode($request);
if ($request == NULL) { // parse error
$error = json_error();
throw new JsonRpcExeption(101, "Parse Error: $error");
}
return $request;
}
// ----------------------------------------------------------------------------
function handle_json_rpc($object) {
try {
$input = get_json_request();
header('Content-Type: application/json');
$method = get_field($input, 'method', null);
$params = get_field($input, 'params', null);
$id = get_field($input, 'id', null);
// json rpc error
if (!($method && $id)) {
if (!$id) {
$id = extract_id();
}
if (!$method) {
$error = "no method";
} else if (!$id) {
$error = "no id";
} else {
$error = "unknown reason";
}
throw new JsonRpcExeption(103, "Invalid Request: $error");
//": " . $GLOBALS['HTTP_RAW_POST_DATA']));
}
// fix params (if params is null set it to empty array)
if (!$params) {
$params = array();
}
// if params is object change it to array
if (is_object($params)) {
if (count(get_object_vars($params)) == 0) {
$params = array();
} else {
$params = get_object_vars($params);
}
}
// call Service Method
$class = get_class($object);
$methods = get_class_methods($class);
if (strcmp($method, "system.describe") == 0) {
echo json_encode(service_description($object));
} else if (!in_array($method, $methods) && !in_array("__call", $methods)) {
// __call will be called for any method that's missing
$msg = "Procedure `" . $method . "' not found";
throw new JsonRpcExeption(104, $msg);
} else {
if (in_array("__call", $methods) && !in_array($method, $methods)) {
$result = call_user_func_array(array($object, $method), $params);
echo response($result, $id, null);
} else {
$method_object = new ReflectionMethod($class, $method);
$num_got = count($params);
$num_expect = $method_object->getNumberOfParameters();
if ($num_got != $num_expect) {
$msg = "Wrong number of parameters. Got $num_got expect $num_expect";
throw new JsonRpcExeption(105, $msg);
} else {
//throw new Exception('x -> ' . json_encode($params));
$result = call_user_func_array(array($object, $method), $params);
echo response($result, $id, null);
}
}
}
} catch (JsonRpcExeption $e) {
// exteption with error code
$msg = $e->getMessage();
$code = $e->code();
if ($code = 101) { // parse error;
$id = extract_id();
}
echo response(null, $id, array("code"=>$code, "message"=>$msg));
} catch (Exception $e) {
//catch all exeption from user code
$msg = $e->getMessage();
echo response(null, $id, array("code"=>200, "message"=>$msg));
}
ob_end_flush();
}
?>