/
ratchet.php
504 lines (429 loc) · 14.4 KB
/
ratchet.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
/*
Plugin Name: Ratchet
Plugin URI: http://github.com/ratchetio/ratchet-wordpress
Description: Monitors and reports PHP errors and exceptions to Ratchet.io
Version: 0.1
Author: Brian Rue
License: MIT
*/
function init_ratchet_plugin() {
$code_root = substr(ABSPATH, 0, strlen(ABSPATH) - 1);
Ratchetio::init(array(
'access_token' => '162db27918c641a19387183bb0319247',
//'max_errno' => 1024, // ignore E_STRICT and beyond
'root' => $code_root,
'base_api_url' => 'http://brian.ratchetdev.com/api/1/'
));
$foo = $baz123;
}
/**
* Singleton-style wrapper around RatchetioNotifier
*
* Unless you need multiple RatchetioNotifier instances in the same project, use this.
*/
class Ratchetio {
public static $instance = null;
public static function init($config, $set_exception_handler = true, $set_error_handler = true) {
self::$instance = new RatchetioNotifier($config);
if ($set_exception_handler) {
set_exception_handler('Ratchetio::report_exception');
}
if ($set_error_handler) {
set_error_handler('Ratchetio::report_php_error');
}
if (self::$instance->batched) {
register_shutdown_function('Ratchetio::flush');
}
}
public static function report_exception($exc) {
if (self::$instance == null) {
return;
}
self::$instance->report_exception($exc);
}
public static function report_message($message, $level = 'error') {
if (self::$instance == null) {
return;
}
self::$instance->report_message($message, $level);
}
public static function report_php_error($errno, $errstr, $errfile, $errline) {
if (self::$instance == null) {
return;
}
self::$instance->report_php_error($errno, $errstr, $errfile, $errline);
}
public static function flush() {
self::$instance->flush();
}
}
class RatchetioNotifier {
const VERSION = "0.2";
// required
public $access_token = '';
// optional / defaults
public $root = '';
public $environment = 'production';
public $branch = 'master';
public $logger = null;
public $base_api_url = 'https://submit.ratchet.io/api/1/';
public $batched = true;
public $batch_size = 50;
public $timeout = 3;
public $max_errno = -1;
private $config_keys = array('access_token', 'root', 'environment', 'branch', 'logger',
'base_api_url', 'batched', 'batch_size', 'timeout', 'max_errno');
// cached values for request/server data
private $_request_data = null;
private $_server_data = null;
// payload queue, used when $batched is true
private $_queue = array();
public function __construct($config) {
foreach ($this->config_keys as $key) {
if (isset($config[$key])) {
$this->$key = $config[$key];
}
}
if (!$this->access_token) {
$this->log_error('Missing access token');
}
}
public function report_exception($exc) {
try {
$this->_report_exception($exc);
} catch (Exception $e) {
try {
$this->log_error("Exception while reporting exception");
} catch (Exception $e) {
// swallow
}
}
}
public function report_message($message, $level = 'error') {
try {
$this->_report_message($message, $level);
} catch (Exception $e) {
try {
$this->log_error("Exception while reporting message");
} catch (Exception $e) {
// swallow
}
}
}
public function report_php_error($errno, $errstr, $errfile, $errline) {
try {
$this->_report_php_error($errno, $errstr, $errfile, $errline);
} catch (Exception $e) {
try {
$this->log_error("Exception while reporting php error");
} catch (Exception $e) {
// swallow
}
}
}
/**
* Flushes the queue.
* Called internally when the queue exceeds $batch_size, and by Ratchetio::flush
* on shutdown.
*/
public function flush() {
$queue_size = count($this->_queue);
if ($queue_size > 0) {
$this->log_info('Flushing queue of size ' . $queue_size);
$this->send_batch($this->_queue);
$this->_queue = array();
}
}
private function _report_exception($exc) {
if (!$this->check_config()) {
return;
}
$data = $this->build_base_data();
// exception info
$frames = $this->build_frames($exc);
$data['body'] = array(
'trace' => array(
'frames' => $this->build_frames($exc),
'exception' => array(
'class' => get_class($exc),
'message' => $exc->getMessage()
)
)
);
// request data
$data['request'] = $this->build_request_data();
// server data
$data['server'] = $this->build_server_data();
$payload = $this->build_payload($data);
$this->send_payload($payload);
}
private function _report_php_error($errno, $errstr, $errfile, $errline) {
if (!$this->check_config()) {
return;
}
if ($this->max_errno != -1 && $errno > $this->max_errno) {
// ignore
return;
}
$data = $this->build_base_data();
// set error level and error constant name
$level = 'info';
$constant = '#' . $errno;
switch ($errno) {
case 2:
$level = 'warning';
$constant = 'E_WARNING';
break;
case 8:
$level = 'info';
$constant = 'E_NOTICE';
break;
case 256:
$level = 'error';
$constant = 'E_USER_ERROR';
break;
case 512:
$level = 'warning';
$constant = 'E_USER_WARNING';
break;
case 1024:
$level = 'info';
$constant = 'E_USER_NOTICE';
break;
case 2048:
$level = 'info';
$constant = 'E_STRICT';
break;
case 4096:
$level = 'error';
$constant = 'E_RECOVERABLE_ERROR';
break;
case 8192:
$level = 'info';
$constant = 'E_DEPRECATED';
break;
case 16384:
$level = 'info';
$constant = 'E_USER_DEPRECATED';
break;
}
$data['level'] = $level;
// use the whole $errstr. may want to split this by colon for better de-duping.
$error_class = $constant . ' ' . $errstr;
// build something that looks like an exception
$data['body'] = array(
'trace' => array(
'frames' => array(array('filename' => $errfile, 'lineno' => $errline)),
'exception' => array(
'class' => $error_class
)
)
);
// request data
$data['request'] = $this->build_request_data();
// server data
$data['server'] = $this->build_server_data();
$payload = $this->build_payload($data);
$this->send_payload($payload);
}
private function _report_message($message, $level) {
if (!$this->check_config()) {
return;
}
$data = $this->build_base_data();
$data['level'] = strtolower($level);
$data['body'] = array(
'message' => array(
'body' => $message
)
);
$data['request'] = $this->build_request_data();
$data['server'] = $this->build_server_data();
$payload = $this->build_payload($data);
$this->send_payload($payload);
}
private function check_config() {
return $this->access_token && strlen($this->access_token) == 32;
}
private function build_request_data() {
if ($this->_request_data === null) {
$request = array(
'url' => $this->current_url(),
'user_ip' => $this->user_ip(),
'headers' => $this->headers(),
'method' => $_SERVER['REQUEST_METHOD'],
);
if ($_GET) {
$request['GET'] = $_GET;
}
if ($_POST) {
$request['POST'] = $_POST;
}
if (isset($_SESSION) && $_SESSION) {
$request['session'] = $_SESSION;
}
$this->_request_data = $request;
}
return $this->_request_data;
}
private function headers() {
$headers = array();
foreach ($_SERVER as $key => $val) {
if (substr($key, 0, 5) == 'HTTP_') {
// convert HTTP_CONTENT_TYPE to Content-Type
$name = strtolower(substr($key, 5));
if (strpos($name, "_") != -1) {
$name = preg_replace("/ /", "-", ucwords(preg_replace('/_/', " ", $name)));
}
$headers[$name] = $val;
}
}
return $headers;
}
private function current_url() {
// should work with apache. not sure about other environments.
$proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
$host = $_SERVER['SERVER_NAME'];
$port = $_SERVER['SERVER_PORT'];
$path = $_SERVER['REQUEST_URI'];
$url = $proto . '://' . $host;
if (($proto == 'https' && $port != 443) || ($proto == 'http' && $port != 80)) {
$url .= ':' . $port;
}
$url .= $path;
return $url;
}
private function user_ip() {
$forwardfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($forwardfor) {
// return everything until the first comma
$parts = preg_split(',', $forwardfor);
return $parts[0];
}
$realip = isset($_SERVER['HTTP_X_REAL_IP']) && $_SERVER['HTTP_X_REAL_IP'];
if ($realip) {
return $realip;
}
return $_SERVER['REMOTE_ADDR'];
}
private function build_frames($exc) {
$frames = array();
foreach ($exc->getTrace() as $frame) {
$frames[] = array(
'filename' => $frame['file'],
'lineno' => $frame['line'],
'method' => $frame['function']
// TODO include args? need to sanitize first.
);
}
// add top-level file and line
$frames[] = array(
'filename' => $exc->getFile(),
'lineno' => $exc->getLine()
);
return $frames;
}
private function build_server_data() {
if ($this->_server_data === null) {
$server_data = array(
'host' => gethostname()
);
if ($this->branch) {
$server_data['branch'] = $this->branch;
}
if ($this->root) {
$server_data['root'] = $this->root;
}
$this->_server_data = $server_data;
}
return $this->_server_data;
}
private function build_base_data($level = 'error') {
return array(
'timestamp' => time(),
'environment' => $this->environment,
'level' => $level,
'language' => 'php',
'framework' => 'php',
'notifier' => array(
'name' => 'ratchet-php',
'version' => self::VERSION
)
);
}
private function build_payload($data) {
return array(
'access_token' => $this->access_token,
'data' => $data
);
}
private function send_payload($payload) {
if ($this->batched) {
if (count($this->_queue) >= $this->batch_size) {
// flush queue before adding payload to queue
$this->flush();
}
$this->_queue[] = $payload;
} else {
$this->_send_payload($payload);
}
}
/**
* Sends a single payload to the /item endpoint.
* $payload - php array
*/
private function _send_payload($payload) {
$this->log_info("Sending payload");
$post_data = json_encode($payload);
$this->make_api_call('item', $post_data);
}
/**
* Sends a batch of payloads to the /batch endpoint.
* A batch is just an array of standalone payloads.
* $batch - php array of payloads
*/
private function send_batch($batch) {
$this->log_info("Sending batch");
$post_data = json_encode($batch);
$this->make_api_call('item_batch', $post_data);
}
private function make_api_call($action, $post_data) {
$url = $this->base_api_url . $action . '/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$result = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code != 200) {
$this->log_warning('Got unexpected status code from Ratchet.io API ' . $action .
': ' .$status_code);
$this->log_warning('Output: ' .$result);
} else {
$this->log_info('Success');
}
}
/* Logging */
private function log_info($msg) {
$this->log_message("INFO", $msg);
}
private function log_warning($msg) {
$this->log_message("WARNING", $msg);
}
private function log_error($msg) {
$this->log_message("ERROR", $msg);
}
private function log_message($level, $msg) {
if ($this->logger !== null) {
$this->logger->log($level, $msg);
}
}
}
init_ratchet_plugin();
?>