-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvarslib.inc.php
More file actions
623 lines (521 loc) · 15.3 KB
/
varslib.inc.php
File metadata and controls
623 lines (521 loc) · 15.3 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<?php
/*
* https://github.com/devsseb/varslib
*
*/
function exists(&$var)
{
if (1 === $count = func_num_args())
return isset($var);
$args = func_get_args();
$_var = &$var;
for ($i = 1; $i < $count; $i++)
if ($exists = (is_object($_var) and (property_exists($_var, $args[$i]) or method_exists($_var, $args[$i]))))
$_var = &$_var->{$args[$i]};
elseif ($exists = (is_array($_var) and array_key_exists($args[$i], $_var)))
$_var = &$_var[$args[$i]];
else
break;
return $exists;
}
/*
Params :
0 : var
... : keys
before last : default value
last :
(bool) check if empty
(array) authorized values
*/
function getDefaultEmpty($var)
{
$keys = func_get_args();
$keys[0] = &$var;
// Last index is $compare
$compare = array_pop($keys);
// Last index is $default
$default = array_pop($keys);
if (call_user_func_array('exists', $keys)) {
$_var = &$keys[0];
$count = count($keys);
for ($i = 1; $i < $count; $i++)
if
(is_object($_var)) $_var = &$_var->{$keys[$i]};
else
$_var = &$_var[$keys[$i]];
if (
$compare === false or
(is_array($compare) and in_array($_var, $compare)) or
($compare === true and !empty($_var))
) {
return $_var;
}
}
return $default;
}
/*
* g &$var
* g &$var, $key1, $key2, $key3, ...
*
*/
function g($var)
{
$args = func_get_args();
$args[0] = &$var;
$args[] = null; // Default value
$args[] = false; // No check if is empty
return call_user_func_array('getDefaultEmpty', $args);
}
/*
* gs &$var
* gs &$var, $key1, $key2, $key3, ...
*
*/
function gs($var)
{
$args = func_get_args();
$args[0] = &$var;
$args[] = ''; // Default value
$args[] = false; // No check if is empty
return call_user_func_array('getDefaultEmpty', $args);
}
/*
* gd &$var, $default
* gd &$var, $key1, $key2, $key3, ..., $default
*
*/
function gd($var)
{
$args = func_get_args();
$args[0] = &$var;
$args[] = false; // No check if is empty
return call_user_func_array('getDefaultEmpty', $args);
}
/*
* gde $var, $default, true|false
* gde $var, $key1, $key2, $key3, ..., $default, true|false|[...]
*
*/
function gde($var)
{
$args = func_get_args();
$args[0] = &$var;
$args[] = true; // Check if is empty
return call_user_func_array('getDefaultEmpty', $args);
}
/*
* gda &$var, $default
* gda &$var, $key1, $key2, $key3, ..., $default, [...,...]
*
*/
function gda($var)
{
$args = func_get_args();
$args[0] = &$var;
return call_user_func_array('getDefaultEmpty', $args);
}
// Same with reference
function gr(&$var) { return call_user_func_array('g', func_get_args()); };
function grd(&$var) { return call_user_func_array('gd', func_get_args()); };
function grde(&$var) { return call_user_func_array('gde', func_get_args()); };
function grda(&$var) { return call_user_func_array('gda', func_get_args()); };
/*
* Error management
*
*/
class ErrorManagement
{
const ERROR_MAIL_MAX = 10;
static protected $mailedCount = 0;
static protected $mails = [];
static protected $throwException = false;
static protected $throwExceptionForNext = false;
static protected $logFile = null;
static public function init()
{
error_reporting(E_ALL | E_STRICT);
set_error_handler([__CLASS__, 'handler']);
register_shutdown_function([__CLASS__, 'handler']);
ini_set('display_errors', 'Off');
}
static public function setLogFile($file)
{
self::$logFile = $file;
}
static public function setMails(array $mails)
{
self::$mails = $mails;
}
static public function throwException($active = true)
{
self::$throwException = (bool)$active;
}
static public function isThrowException()
{
return self::$throwException;
}
// Throw exception on error and immediately disabled throwException option
static public function throwExceptionForNext()
{
self::throwException();
self::$throwExceptionForNext = true;
}
static public function stopThrowExceptionForNext(bool $throwException = true, $message = 'An unknown exception has occurred')
{
self::throwException(false);
if ($throwException) {
$backtrace = debug_backtrace();
throw new \ErrorHandledException($message, 0, E_USER_ERROR, g($backtrace, 0, 'file'), g($backtrace, 0, 'line'));
}
}
static public function handler($type = null, $message = null, $file = null, $line = null)
{
if ($type === null) {
$error = error_get_last();
$type = g($error, 'type');
$message = preg_capture('#([\s\S]+)\nStack trace:#', gd($error, 'message', ''));
if (!$message)
$message = gd($error, 'message', '');
$file = g($error, 'file');
$line = g($error, 'line');
}
if (self::isThrowException()) {
if (self::$throwExceptionForNext) {
self::$throwExceptionForNext = false;
self::throwException(false);
}
throw new \ErrorHandledException($message, 0, $type === null ? E_ERROR : $type, $file, $line);
}
if ($message) {
$exit = !in_array($type, array(E_WARNING, E_NOTICE, E_USER_WARNING, E_USER_NOTICE, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED));
if ($exit or \Debug::isActive() or self::$logFile) {
if ($type === E_ERROR) // 1
$typeStringify = 'E_ERROR';
elseif ($type === E_WARNING) // 2
$typeStringify = 'E_WARNING';
elseif ($type === E_PARSE) // 4
$typeStringify = 'E_PARSE';
elseif ($type === E_NOTICE) // 8
$typeStringify = 'E_NOTICE';
elseif ($type === E_CORE_ERROR) // 16
$typeStringify = 'E_CORE_ERROR';
elseif ($type === E_CORE_WARNING) // 32
$typeStringify = 'E_CORE_WARNING';
elseif ($type === E_COMPILE_ERROR) // 64
$typeStringify = 'E_COMPILE_ERROR';
elseif ($type === E_COMPILE_WARNING) // 128
$typeStringify = 'E_COMPILE_WARNING';
elseif ($type === E_USER_ERROR) // 256
$typeStringify = 'E_USER_ERROR';
elseif ($type === E_USER_WARNING) // 512
$typeStringify = 'E_USER_WARNING';
elseif ($type === E_USER_NOTICE) // 1024
$typeStringify = 'E_USER_NOTICE';
elseif ($type === E_STRICT) // 2048
$typeStringify = 'E_STRICT';
elseif ($type === E_RECOVERABLE_ERROR) // 4096
$typeStringify = 'E_RECOVERABLE_ERROR';
elseif ($type === E_DEPRECATED) // 8192
$typeStringify = 'E_DEPRECATED';
elseif ($type === E_USER_DEPRECATED) // 16384
$typeStringify = 'E_USER_DEPRECATED';
else
$typeStringify = 'unknown';
}
if ($exit or \Debug::isActive()) {
$detailledMessage =
'An error ' . $typeStringify . ' occurred' . chr(10) .
'Message : '. $message . chr(10) .
'File : ' . $file . chr(10) .
'Line : ' . $line
;
$stack = debug_backtrace();
array_shift($stack);
foreach ($stack as $i => $stackLine) {
$args = array();
foreach (gd($stackLine, 'args', array()) as $arg) {
if (is_array($arg))
$args[] = 'Array(' . count($arg) . ')';
elseif (is_null($arg))
$args[] = 'null';
elseif (is_string($arg))
$args[] = '"' . substr($arg, 0, 25) . (strlen($arg) > 25 ? '...' : '') . '"';
elseif (is_bool($arg))
$args[] = $arg ? 'true' : 'false';
elseif (is_object($arg))
$args[] = 'Object(' . get_class($arg) . ')';
elseif (is_numeric($arg))
$args[] = $arg;
else
$args[] = '<' . $arg . '>';
}
$function = $stackLine['function'];
if (array_key_exists('class', $stackLine)) {
$function = $stackLine['class'];
$function.= $stackLine['type'];
$function.= $stackLine['function'];
}
if ($i === 0)
$detailledMessage.= chr(10) . 'Stack : ';
$detailledMessage.= chr(10) . chr(9) . '[' . $i . '] Function : ' . $function . '(' . implode(',', $args) . ')';
$detailledMessage.= chr(10) . chr(9) . chr(9) . 'File : ' . (array_key_exists('file', $stackLine) ? $stackLine['file'] : 'unknown');
$detailledMessage.= chr(10) . chr(9) . chr(9) . 'Line : ' . (array_key_exists('line', $stackLine) ? $stackLine['line'] : 'unknown');
}
if (\Debug::isActive() and self::$mails and self::$mailedCount <= self::ERROR_MAIL_MAX) {
$last = '';
if (self::$mailedCount == self::ERROR_MAIL_MAX)
$last = ' (max error reached for mail)';
mail(implode(';', self::$mails), 'PHP Error on ' . gd($_SERVER, 'SCRIPT_URI', php_uname('n')) . $last,
$detailledMessage . chr(10) .
'$_SERVER : ' . print_r(array_diff_key($_SERVER, array('REMOTE_USER' => null, 'PHP_AUTH_USER' => null, 'PHP_AUTH_PW' => null)), true) . chr(10) .
'$_SESSION : ' . (isset($_SESSION) ? print_r($_SESSION, true) : 'null')
);
self::$mailedCount++;
}
}
if (self::$logFile) {
$simplifiedMessage = 'An error ' . $typeStringify . ' occurred : "' . $message . '" on line ' . $line . ' in ' . $file;
file_put_contents(self::$logFile, date('Y-m-d H:i:s') . ' ' . $simplifiedMessage . chr(10), FILE_APPEND);
}
if ($exit and !\Debug::isActive()) {
http_response_code(500);
exit('An error ' . $typeStringify . ' occurred');
}
if (\Debug::isActive())
\Debug::trace([
'style' => 'error',
'label' => 'ERROR',
'exit' => $exit,
'messages' => [$detailledMessage]
]);
}
}
}
class ErrorHandledException extends \ErrorException{}
/*
* DEBUG
*
*/
class Debug {
static public $traceHtmlStyles = [
'container' => [
'default' => 'border:1px solid #335AE8;text-align:left;margin:1px 0px;overflow:auto;color:#000;font:12px monospace;',
'error' => 'border-color:#ff0000;'
],
'line' => [
'odd' => [
'default' => 'margin:0px;background-color:#C5DAFF;color:inherit;font-size:inherit;padding:inherit;line-height:inherit;border:none;',
'error' => 'background-color:#ff8e8e;'
],
'even' => [
'default' => 'margin:0px;background-color:#D9E6FF;color:inherit;font-size:inherit;padding:inherit;line-height:inherit;border:none;',
'error' => 'background-color:#ff8e8e;'
]
]
];
static public $traceCliStyles = [
'char' => '░',
'len' => 64
];
static public $colors = [];
static public $styles = [];
static protected $active = false;
static protected $html = false;
static protected $chronos = [];
static public function init()
{
\ErrorManagement::init();
self::html(php_sapi_name() != 'cli' and PHP_SAPI != 'cli');
}
static public function getTraceHtmlStyles()
{
return self::$traceHtmlStyles;
}
static public function setTraceHtmlStyles($traceHtmlStyles)
{
self::$traceHtmlStyles = $traceHtmlStyles;
}
static public function active($active = true)
{
self::$active = (bool)$active;
}
static public function isActive()
{
return self::$active;
}
static public function html($html = true)
{
self::$html = (bool)$html;
}
static public function isHtml()
{
return self::$html;
}
static public function trace(array $options)
{
$label = (array_key_exists('label', $options) ? $options['label'] : 'TRACE');
$exit = (array_key_exists('exit', $options) ? $options['exit'] : false);
$style = (array_key_exists('style', $options) ? $options['style'] : 'default');
$messages = $options['messages'];
if (self::isActive()) {
if (self::isHtml()) {
echo '<div style="' . self::$traceHtmlStyles['container'][$style] . '">';
foreach ($messages as $index => $message) {
echo chr(9) . '<pre style="' . self::$traceHtmlStyles['line'][$index%2 == 0 ? 'odd' : 'even'][$style] . '">' . chr(10);
$message = print_r(self::traceMessageToHtml($message), true);
echo preg_replace('/(\\[.*?\\])( => .*?\n\\()/', '<strong>$1</strong>$2', $message);
echo chr(10) . '</pre>';
}
echo '</div>';
} else {
$strlen = 'strlen';
if (function_exists('mb_strlen'))
$strlen = 'mb_strlen';
foreach ($messages as $index => $message) {
$label = self::$traceCliStyles['char'] . $label . (count($messages) > 1 ? self::$traceCliStyles['char'] . ($index + 1) : '');
echo $label . str_repeat(self::$traceCliStyles['char'], self::$traceCliStyles['len'] - $strlen($label)) . chr(10);
print_r($message);
echo chr(10);
}
echo str_repeat(self::$traceCliStyles['char'], self::$traceCliStyles['len']) . chr(10);
}
if ($exit)
exit();
}
}
static protected function traceMessageToHtml($message)
{
$result = '';
if (is_array($message)) {
foreach ($message as &$value)
$value = self::traceMessageToHtml($value);
unset($value);
$result = $message;
} elseif (is_null($message))
$result = '<span style="font-style:italic;">null</span>';
elseif ($message === '')
$result = '<span style="font-style:italic;">empty string</span>';
elseif (is_string($message))
$result = toHtml($message);
elseif (is_bool($message))
$result = '<span style="font-style:italic;">' . ($message ? 'true' : 'false') . '</span>';
else
$result = print_r($message, true);
return $result;
}
static public function chronoStart($id = '')
{
self::$chronos[$id] = explode(' ', microtime());
}
static public function chronoGet($id = '')
{
$start = gd(self::$chronos, $id, [0,0]);
$time = explode(' ', microtime());
return $time[1] + $time[0] - $start[1] - $start[0];
}
}
\Debug::init();
function trace(...$messages)
{
call_user_func(['\\Debug', 'trace'], [
'messages' => $messages
]);
}
function quit(...$messages)
{
call_user_func(['\\Debug', 'trace'], [
'exit' => true,
'label' => 'QUIT',
'messages' => $messages
]);
}
function tracec()
{
$style = \Debug::getTraceHtmlStyles();
$currentStyle = $style['container']['default'];
$args = func_get_args();
$style['container']['default'].= 'color:' . array_shift($args) . ';';
\Debug::setTraceHtmlStyles($style);
call_user_func_array('trace', $args);
$style['container']['default'] = $currentStyle;
\Debug::setTraceHtmlStyles($style);
}
/*
* MISC
*
*/
function toHtml($string, $flag = ENT_QUOTES)
{
if (is_array($string))
return array_map('toHtml', $string);
$string = htmlentities((string)$string, $flag, 'UTF-8');
$string = preg_replace('/\\xC2\\x80/i', '€', $string); //€
return $string;
}
function in_dir($dir, $file, $exists = false)
{
if ($file === null)
$file = '';
$realDir = realpath($dir);
if (!$realDir)
$realDir = $dir;
$element = realpath(dirname($file)) . '/' . basename($file);
$result = strpos($element, $realDir) === 0;
if ($result and $exists)
$result = file_exists($file);
return $result;
}
function array_index($array, $keys, $keySeparator = ',')
{
if (!is_array($keys))
$keys = [$keys];
$indexedArray = [];
foreach ($array as $line) {
$dataKey = [];
foreach ($keys as $key)
$dataKey[] = $line[$key];
$indexedArray[implode($keySeparator, $dataKey)] = $line;
}
return $indexedArray;
}
function array_index_duplicated($array, $keys, $keySeparator = ',')
{
if (!is_array($keys))
$keys = [$keys];
$indexedArray = [];
foreach ($array as $line) {
$dataKey = [];
foreach ($keys as $key)
$dataKey[] = $line[$key];
$dataKey = implode($keySeparator, $dataKey);
if (!array_key_exists($dataKey, $indexedArray))
$indexedArray[$dataKey] = [];
$indexedArray[$dataKey][] = $line;
}
return $indexedArray;
}
function preg_capture_all($pattern, $subject)
{
if (!is_string($subject))
$subject = '';
preg_match($pattern, $subject, $match);
if (count($match) > 1)
array_shift($match);
return $match;
}
function preg_capture($pattern, $subject)
{
return g(preg_capture_all($pattern, $subject), 0);
}
function exit_json($data, $addcontenttype = true)
{
if ($addcontenttype)
header('Content-type: application/json');
header('x-content-type-options: nosniff');
exit(json_encode($data));
}
function http_parse_query($query)
{
parse_str($query, $output);
return $output;
}