-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebapp.php
More file actions
1404 lines (1379 loc) · 43.5 KB
/
webapp.php
File metadata and controls
1404 lines (1379 loc) · 43.5 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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
require 'webapp_filter.php';
require 'webapp_client.php';
require 'webapp_dom.php';
require 'webapp_echo.php';
class_exists('GdImage') && require 'webapp_image.php';
class_exists('mysqli') && require 'webapp_mysql.php';
class_exists('Redis') && require 'webapp_redis.php';
interface webapp_io
{
function request_ip():string;
function request_time():int;
function request_scheme():string;
function request_method():string;
function request_query():string;
function request_into():string;
function request_header(string $name):?string;
function request_cookie(string $name):?string;
function request_content():string;
function request_formdata():array;
function request_uploadedfile():array;
function response_sent():bool;
function response_status(int $code):void;
function response_header(string $value):void;
function response_cookie(float|string ...$values):void;
function response_content(string $data):bool;
function response_sendfile(string $filename):bool;
}
abstract class webapp extends stdClass implements ArrayAccess, Stringable, Countable
{
const version = '4.7.1b', key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz-', sign = 'xxh3';
public readonly self $webapp;
public readonly array $query;
public readonly string $into;
public object|string $router;
public string $method;
private array $errors = [], $cookies = [], $headers = [], $uploadedfiles, $configs, $route, $entry;
private static array $lib = [], $remote = [];
static function lib(string $filename, ...$parameters):mixed
{
static::$lib[$name = strtolower($filename)] ??= (require is_file($name) ? $name : __DIR__ . "/library/{$name}") ?? 1;
return $parameters && is_callable(static::$lib[$name]) ? static::$lib[$name](...$parameters) : static::$lib[$name];
}
static function simplified_chinese(string $content):string
{
return static::lib('utf8_chinese/simplified.php', $content);
}
static function mime(string $filename):string
{
return static::lib('fileinfo/mime.php', $filename);
}
static function ffmpeg(string ...$filename):Closure|webapp_ffmpeg_interface
{
return static::lib('ffmpeg/interface.php', ...$filename);
}
static function qrcode(string $data, int $ecc = 0):IteratorAggregate&Countable
{
return static::lib('misc/qrcode_encode.php', $data, $ecc);
}
static function debugtimer(?float &$time = 0):float
{
return $time = microtime(TRUE) - $time;
}
static function time(int $offset = 0):int
{
return time() + $offset;
}
static function sign(string $data):int
{
return hexdec(substr(hash(static::sign, $data, FALSE), -15));
}
static function signreduce(int $code, bool $care):string
{
for ($hash = '', [$i, $n, $b] = $care ? [10, 6, 63] : [12, 5, 31]; $i;)
{
$hash .= self::key[$code >> --$i * $n & $b];
}
return $hash;
}
static function signrevert(string $hash):int
{
for ($code = 0, $i = 0, [$n, $b, $data] = strlen($hash) === 10
? [6, 54, $hash] : [5, 55, strtoupper(substr($hash, 0, 12))]; isset($data[$i]); ++$i) {
$code |= strpos(self::key, $data[$i]) << $b - $i * $n;
}
return $code;
}
static function hash(string $data, bool $care = FALSE):string
{
return static::signreduce(static::sign($data), $care);
}
static function hashfile(string $filename, bool $care = FALSE):?string
{
return is_file($filename) && is_string($hex = hash_file(static::sign, $filename, FALSE))
? static::signreduce(hexdec(substr($hex, -15)), $care) : NULL;
}
static function random(int $length):string
{
return random_bytes($length);
}
static function random_int(int $min, int $max):int
{
return random_int($min, $max);
}
static function random_code():int
{
return static::sign(static::random(8));
}
static function random_hash(bool $care):string
{
return static::hash(static::random(8), $care);
}
static function random_weight(array $items, string $key = 'weight'):array
{
if ($items)
{
$weight = array_combine(array_keys($items), array_column($items, $key));
$random = static::random_int($current = 0, max(0, array_sum($weight) - 1));
foreach ($weight as $index => $value)
{
if ($random >= $current && $random < $current + $value)
{
break;
}
$current += $value;
}
return $items[$index];
}
return $items;
}
static function shuffle(array $list)
{
}
static function iphex(string $ip):string
{
return str_pad(bin2hex(inet_pton($ip)), 32, '0', STR_PAD_LEFT);
}
static function hexip(string $hex):string
{
return inet_ntop(hex2bin($hex));
}
static function url64_encode(string $data):string
{
for ($i = 0, $length = strlen($data), $buffer = ''; $i < $length;)
{
$value = ord($data[$i++]) << 16;
$buffer .= self::key[$value >> 18 & 63];
if ($i < $length)
{
$value |= ord($data[$i++]) << 8;
$buffer .= self::key[$value >> 12 & 63];
if ($i < $length)
{
$value |= ord($data[$i++]);
$buffer .= self::key[$value >> 6 & 63];
$buffer .= self::key[$value & 63];
continue;
}
$buffer .= self::key[$value >> 6 & 63];
break;
}
$buffer .= self::key[$value >> 12 & 63];
break;
}
return $buffer;
}
static function url64_decode(string $data):?string
{
do
{
if (rtrim($data, self::key))
{
break;
}
for ($i = 0, $length = strlen($data), $buffer = ''; $i < $length;)
{
$value = strpos(self::key, $data[$i++]) << 18;
if ($i < $length)
{
$value |= strpos(self::key, $data[$i++]) << 12;
$buffer .= chr($value >> 16 & 255);
if ($i < $length)
{
$value |= strpos(self::key, $data[$i++]) << 6;
$buffer .= chr($value >> 8 & 255);
if ($i < $length)
{
$buffer .= chr($value | strpos(self::key, $data[$i++]) & 255);
}
}
continue;
}
break 2;
}
return $buffer;
} while (0);
return NULL;
}
static function encrypt(?string $data):?string
{
return is_string($data)
&& is_string($binary = openssl_encrypt($data, 'aes-128-gcm', static::key, OPENSSL_RAW_DATA,
$iv = static::random(12), $tag, '', 16)) ? static::url64_encode($iv . $binary . $tag) : NULL;
}
static function decrypt(?string $data):?string
{
return is_string($data) && strlen($data) > 37
&& is_string($binary = static::url64_decode($data))
&& is_string($result = openssl_decrypt(substr($binary, 12, -16), 'aes-128-gcm', static::key, OPENSSL_RAW_DATA,
substr($binary, 0, 12), substr($binary, -16), '')) ? $result : NULL;
}
static function signature(string $username, string $password, string $additional = NULL):?string
{
return static::encrypt(pack('PCCa*', static::time(), strlen($username), strlen($password), $username . $password . $additional));
}
static function authorize(?string $signature, callable $authenticate):array
{
return is_string($data = static::decrypt($signature))
&& strlen($data) > 5
&& extract(unpack('Psigntime/C2length', $data)) === 3
&& strlen($data) > 5 + $length1 + $length2
&& is_array($acc = unpack("a{$length1}uid/a{$length2}pwd/a*add", $data, 10))
? $authenticate($acc['uid'], $acc['pwd'], $signtime, $acc['add']) : [];
}
static function captcha_random(int $length, int $expire):?string
{
$random = static::random($length * 3);
for ($i = 0; $i < $length; ++$i)
{
$random[$i] = chr((ord($random[$i]) % 26) + 65);
}
return static::encrypt(pack('PCa*', static::time($expire), $length, $random));
}
static function captcha_result(?string $random):?array
{
if (is_string($binary = static::decrypt($random))
&& strlen($binary) > 4
&& extract(unpack('Pexpire/Clength', $binary)) === 2
&& strlen($binary) > 4 + $length * 3
&& is_array($values = unpack("a{$length}code/c{$length}size/c{$length}angle", $binary, 9))) {
if ($length > 1)
{
for ($result = [$expire, '', [], []], $i = 0; $i < $length;)
{
$result[1] .= $values['code'][$i++];
$result[2][] = $values["size{$i}"];
$result[3][] = $values["angle{$i}"];
}
return $result;
}
return [$expire, $values['code'], [$values['size']], [$values['angle']]];
}
return NULL;
}
static function captcha_verify(string $random, string $answer):bool
{
return is_array($result = static::captcha_result($random)) && $result[0] > static::time() && $result[1] === strtoupper($answer);
}
static function xml(mixed ...$params):webapp_xml
{
try
{
libxml_clear_errors();
libxml_use_internal_errors(TRUE);
$xml = new webapp_xml(...$params);
}
catch (Throwable $errors)
{
$xml = new webapp_xml('<errors/>');
$xml->cdata((string)$errors);
foreach (libxml_get_errors() as $error)
{
$xml->append('error', [
'level' => $error->level,
'code' => $error->code,
'line' => $error->line
])->cdata($error->message);
}
}
libxml_use_internal_errors(FALSE);
return $xml;
}
// static function iterator(iterable ...$aggregate):iterable
// {
// foreach ($aggregate as $iter)
// {
// foreach ($iter as $item)
// {
// yield $item;
// }
// }
// }
// static function filenameescape(string $basename):string
// {
// return str_replace(['\\', '/', ':', '*', '?', '"', '<', '>'], '_', $basename);
// }
// static function build_test_router(bool $dataurl = FALSE, ...$urls):string
// {
// $code = stream_get_line(fopen(__DIR__ . '/static/js/test_router.js', 'r'), 0xffff, "\n");
// $code = str_replace('{ERRORPAGE}', array_shift($urls), $code);
// $code = str_replace('{BASE64URLS}', base64_encode(join(',', $urls)), $code);
// return $dataurl
// ? 'data:text/html;base64,' . base64_encode("<script>{$code}</script>")
// : 'javascript:eval(atob(\''. base64_encode($code) .'\'));';
// //: 'javascript:'. rawurlencode($code) .';';
// //: 'javascript:Function(atob(\''. base64_encode($code) .'\'))();';
// }
// static function encryptdata(string $content, string $key)
// {
// $iv = static::random(12);
// $en = openssl_encrypt($content, 'aes-128-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16);
// return $iv . $en . $tag;
// }
static function masker($stream, string &$key = NULL, bool $merged = FALSE)
{
$key ??= static::random(8);
return is_resource(is_string($stream) ? $stream = fopen($stream, 'r') : $stream)
&& is_resource(stream_filter_append($stream, 'webapp.filter_mask.encode', STREAM_FILTER_READ,
$merged ? $key : array_map(ord(...), str_split($key)))) ? $stream : NULL;
}
static function unmasker($stream, string $key = NULL)
{
return is_resource(is_string($stream) ? $stream = fopen($stream, 'r') : $stream)
&& is_resource(stream_filter_append($stream, 'webapp.filter_mask.decode', STREAM_FILTER_READ,
$key ? array_map(ord(...), str_split($key)) : NULL)) ? $stream : NULL;
}
static function maskfile($from, $to, string &$key = NULL, bool $merged = FALSE):bool
{
return is_resource($stream = static::masker($from, $key, $merged))
&& is_resource(is_string($to) ? $to = fopen($to, 'w') : $to)
&& stream_copy_to_stream($stream, $to) !== FALSE
&& feof($stream);
}
static function maskdata(string $data, string &$key = NULL, bool $merged = FALSE):?string
{
return is_resource($stream = fopen('php://memory', 'w+'))
&& fwrite($stream, $data) === strlen($data)
&& is_resource(static::masker($stream, $key, $merged))
&& rewind($stream)
&& is_string($result = stream_get_contents($stream)) ? $result : NULL;
}
static function unmaskfile($from, $to, string $key = NULL):bool
{
return is_resource($stream = static::unmasker($from, $key))
&& is_resource(is_string($to) ? $to = fopen($to, 'w') : $to)
&& stream_copy_to_stream($stream, $to) !== FALSE
&& feof($stream);
}
static function unmaskdata(string $data, string $key = NULL):?string
{
return is_resource($stream = fopen('php://memory', 'w+'))
&& fwrite($stream, $data) === strlen($data)
&& is_resource(static::unmasker($stream, $key))
&& rewind($stream)
&& is_string($result = stream_get_contents($stream)) ? $result : NULL;
}
function __construct(array $config = [], private readonly webapp_io $io = new webapp_stdio)
{
[$this->webapp, $this->into, $this->configs] = [$this, $io->request_into(), $config + [
//Request
'request_method' => in_array($method = strtolower($io->request_method()), ['cli', 'get', 'post', 'put', 'patch', 'delete', 'options'], TRUE) ? $method : 'get',
'request_query' => $io->request_query(),
//Application
'app_charset' => 'utf-8',
'app_locale' => 'zh-CN',
'app_router' => 'webapp_router_',
'app_index' => 'home',
//Admin
'admin_username' => 'admin',
'admin_password' => 'nimda',
'admin_cookie' => 'webapp',
'admin_expire' => 604800,
//Captcha
'captcha_length' => 4,
'captcha_expire' => 99,
'captcha_params' => [210, 86, __DIR__ . '/static/fonts/ArchitectsDaughter_R.ttf', 28],
//QRCode
'qrcode_echo' => TRUE,
'qrcode_ecc' => 0,
'qrcode_maxdata' => 1024,
'qrcode_pixel' => 4,
//MySQL
'mysql_hostname' => 'p:127.0.0.1:3306',
'mysql_username' => 'root',
'mysql_password' => '',
'mysql_database' => 'webapp',
'mysql_maptable' => 'webapp_maptable_',
'mysql_charset' => 'utf8mb4',
//Redis
'redis_open' => ['127.0.0.1', 6379],
'redis_auth' => [],
//Misc
'copy_webapp' => 'Web Application v' . self::version,
'smtp_url' => 'ssl://user:pass@smtp.gmail.com:465',
'gzip_level' => -1,
'manifests' => [],]];
[$this->route, $this->entry] = method_exists($this, $route = sprintf('%s_%s', $this['request_method'],
$track = preg_match('/^[-\w]+(?=\/([\-\w]*))?/', $this['request_query'], $entry)
? strtr($entry[0], '-', '_') : $entry[] = $this['app_index']))
? [[$this, $route], array_slice($entry, 1)]
: [[$this['app_router'] . $track, sprintf('%s_%s', $this['request_method'],
count($entry) > 1 ? strtr($entry[1], '-', '_') : $this['app_index'])], []];
[&$this->router, &$this->method] = $this->route;
$this->query = preg_match_all('/\,(\w+)(?:\:([\%\+\-\.\/\=\w]*))?/', $this['request_query'],
$pattern, PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL) ? array_column($pattern, 2, 1) : [];
if (method_exists($this, 'authenticate'))
{
$this->auth = [];
if (method_exists(...$this->route)
&& in_array($this->method, ['get_captcha', 'get_qrcode', 'get_favicon', 'get_manifests', 'get_masker']) === FALSE
&& empty($this->auth = $this->auth($this->authenticate(...)))) {
($this->router === $this || $this->router === $this['app_router'] . $this['app_index'])
&& $this->method === "get_{$this['app_index']}" ? $this->echo_html(authenticate: $this) : $this->response_status(401);
}
}
}
function __destruct()
{
do
{
if (method_exists(...$this->route) && ($tracert = new ReflectionMethod(...$this->route))->isPublic())
{
do
{
if (($router = is_string($this->router)
&& ($method = new $this->router($this))::class === $this->router
? $method : $this->router)::class === 'Closure') {
$status = $router(...$this->entry);
}
else
{
if ($tracert->isUserDefined() === FALSE)
{
break;
}
if ($this->query)
{
foreach (array_slice($tracert->getParameters(), intval($router === $this)) as $parameter)
{
if (array_key_exists($parameter->name, $this->query))
{
$this->entry[$parameter->name] ??= match ((string)$parameter->getType())
{
'int' => intval($this->query[$parameter->name]),
'float' => floatval($this->query[$parameter->name]),
'string' => (string)$this->query[$parameter->name],
default => $this->query[$parameter->name]
};
continue;
}
if ($parameter->isOptional() === FALSE)
{
break 2;
}
}
}
if ($tracert->getNumberOfRequiredParameters() > count($this->entry))
{
break;
}
$status = $tracert->invoke($router, ...$this->entry);
}
$tracing = property_exists($this, 'echo') ? $this->echo : $method ?? $router;
if ($tracing !== $this && $tracing instanceof Stringable)
{
$this->echo((string)$tracing);
}
break 2;
} while (0);
}
$status = 404;
} while (0);
if ($this->io->response_sent() === FALSE)
{
if (is_int($status))
{
$this->io->response_status($status);
}
foreach ($this->cookies as $values)
{
$this->io->response_cookie(...$values);
}
foreach ($this->headers as $name => $value)
{
$this->io->response_header("{$name}: {$value}");
}
if (property_exists($this, 'buffer'))
{
if ($this['gzip_level']
&& ftell($this->buffer)
&& is_string($encoding = $this->request_header('Accept-Encoding'))
&& stripos($encoding, 'gzip') !== FALSE
&& stream_filter_append($this->buffer, 'zlib.deflate', STREAM_FILTER_READ,
['level' => $this['gzip_level'], 'window' => 31, 'memory' => 9])) {
$this->io->response_header('Content-Encoding: gzip');
}
// $this->io->response_header('Content-Length: ' . strlen($data = (string)$this));
// $this->io->response_content($data);
$this->io->response_content((string)$this);
unset($this->buffer);
}
}
}
// function __debugInfo()
// {
// return ['query' => $this->query, 'into' => $this->into, 'route' => $this->route];
// }
function __toString():string
{
return stream_get_contents($this->buffer, -rewind($this->buffer));
}
function __get(string $name):mixed
{
if (method_exists($this, $name))
{
$loader = new ReflectionMethod($this, $name);
if ($loader->isPublic() && $loader->getNumberOfRequiredParameters() === 0)
{
return $this->{$name} = $loader->invoke($this);
}
}
throw new Error;
}
final function __invoke(object $object):object
{
if (property_exists($object, 'webapp') && isset($object->webapp) === FALSE)
{
$object->webapp = $this;
}
if ($object instanceof ArrayAccess)
{
$object['errors'] = &$this->errors;
}
else
{
$object->errors = &$this->errors;
}
return $object;
}
final function offsetExists(mixed $key):bool
{
return array_key_exists($key, $this->configs);
}
final function &offsetGet(mixed $key):mixed
{
return $this->configs[$key];
}
final function offsetSet(mixed $key, mixed $value):void
{
$this->configs[$key] = $value;
}
final function offsetUnset(mixed $key):void
{
unset($this->configs[$key]);
}
final function count():int
{
return property_exists($this, 'buffer') ? ftell($this->buffer) : 0;
}
// final function app(string $name, mixed ...$params):object
// {
// return $this($this->echo = new $name($this, ...$params));
// }
final function break(Closure|array $router, mixed ...$params):void
{
[$this->route[0], $this->route[1]] = [$router, '__invoke'];
if (func_num_args() > 1)
{
$this->entry = $params;
}
}
final function entry(array $params):void
{
$this->entry = $params + $this->entry;
}
final function buffer():mixed
{
return fopen('php://memory', 'r+');
}
function locale(&$set, string $prefix, string ...$locales):string
{
static $local = (fn($locale, $language) => [...$locale ? [$locale] : [], ...$language
? array_map(fn($v) => strstr("{$v};", ';', TRUE), explode(',', $language)) : []])
($this->io->request_cookie('locale'), $this->io->request_header('Accept-Language'));
$localed = $this['app_locale'];
foreach ($local as $locale)
{
if (in_array($locale, $locales, TRUE))
{
$localed = $locale;
break;
}
}
$set = require "{$prefix}{$localed}.php";
return $localed;
}
function locales(&$set):string
{
return $this->locale($set, __DIR__ . '/extend/locale/', 'zh-CN', 'en', 'km-KH', 'ja-JP', 'ko');
}
function nonematch(?string $etag):bool
{
$this->response_header('Etag', $hash = '"' . static::hash($etag ?? $this['request_query'], TRUE) . '"');
return $this->request_header('If-None-Match') !== $hash;
}
function webappxml():webapp_xml
{
return static::xml(sprintf('<?xml version="1.0" encoding="%s"?><webapp version="%s"/>', $this['app_charset'], self::version));
}
function at(array $params, string $router = NULL):string
{
return array_reduce(array_keys($replace = array_reverse($params + $this->query, TRUE)),
fn($carry, $key) => is_scalar($replace[$key])
? (is_bool($replace[$key]) ? $carry : "{$carry},{$key}:{$replace[$key]}")
: "{$carry},{$key}", $router ?? strstr("?{$this['request_query']},", ',', TRUE));
}
#iconv
function iconv(string $encoding, string $text):?string
{
return is_string($data = @iconv($encoding, $this['app_charset'], $text)) ? $data : NULL;
}
function strlen(string $text):int
{
return iconv_strlen($text, $this['app_charset']);
}
function substr(string $text, int $offset, ?int $length = NULL):string
{
return iconv_substr($text, $offset, $length, $this['app_charset']);
}
#echo
function echo(string $data):bool
{
return fwrite($this->buffer, $data) === strlen($data);
}
function printf(string $format, string ...$params):int
{
return fprintf($this->buffer, $format, ...$params);
}
function println(string $data):int
{
return $this->printf("%s\n", $data);
}
function putcsv(array $values, string $delimiter = ',', string $enclosure = '"'):int
{
return fputcsv($this->buffer, $values, $delimiter, $enclosure);
}
// function echo_object(string|object $instance, mixed ...$params):object
// {
// return $this($this->echo = is_string($instance) ? new ${"$instance"}($this, ...$params) : $instance);
// }
function echo_xml(string $type = 'webapp', string ...$params):webapp_echo_xml
{
return $this->echo = new webapp_echo_xml($this, $type, ...$params);
}
function echo_svg(array $attributes = []):webapp_echo_svg
{
return $this->echo = new webapp_echo_svg($this, $attributes);
}
function echo_json(array|object $data = []):webapp_echo_json
{
return $this($this->echo = new webapp_echo_json($this, $data));
}
function echo_html(string $title = NULL, webapp|string $authenticate = NULL):webapp_echo_html
{
$this->echo = new webapp_echo_html($this, $authenticate);
is_string($title) && $this->echo->title($title);
return $this->echo;
}
function routename():string
{
return strtr(substr(...is_string($this->router)
? [$this->router, strlen($this['app_router'])]
: [$this->method, strlen($this['request_method']) + 1]), '_', '-');
}
function admin(string $username, string $password, int $signtime, string $additional = NULL):array
{
return $signtime > static::time(-$this['admin_expire'])
&& $username === $this['admin_username']
&& $password === $this['admin_password']
? [$username, $password, $additional] : [];
}
function auth(callable $authenticate = NULL, ?string $storage = NULL):array
{
return static::authorize($this->request_authorization($type)
?? $this->request_cookie($storage ?? $this['admin_cookie']), $authenticate
?? $this->admin(...));
}
// function request_authorized(callable $authenticate = NULL, string $storage = NULL)
// {
// $this->request_auth_cookie($this['admin_cookie']);
// $this->request_authorization($type)
// }
// function admin(?string $signature = NULL):array
// {
// return static::authorize(func_num_args() ? $signature : $this->request_cookie($this['admin_cookie']), $this->authenticate(...));
// }
// function authenticate(string $username, string $password, int $signtime, string $additional):array
// {
// return $signtime > static::time(-$this['admin_expire'])
// && $username === $this['admin_username']
// && $password === $this['admin_password']
// ? [$username, $password, $additional] : [];
// }
// function authorization(Closure $authenticate = NULL):array
// {
// return $authenticate
// ? static::authorize($this->request_authorization(), $authenticate)
// : $this->admin($this->request_authorization());
// }
// function authorized(string $additional = NULL):array
// {
// return ['Authorization' => 'Bearer ' . static::signature($this['admin_username'], $this['admin_password'], $additional)];
// }
//---------------------
function smtp(string $url = NULL):webapp_client_smtp
{
return new webapp_client_smtp($url ?? $this['smtp_url']);
}
function open(string $url, array $options = []):webapp_client_http
{
// $options['headers']['Authorization'] ??= 'Bearer ' . static::signature($this['admin_username'], $this['admin_password']);
$options['headers']['User-Agent'] ??= 'WebApp/' . self::version;
return webapp_client_http::open($url, $options);
// return $this(new webapp_client_http($url, $timeout))->headers([
// 'Authorization' => 'Digest ' . static::signature($this['admin_username'], $this['admin_password']),
// 'User-Agent' => 'WebApp/' . self::version
// ]);
// $client = new webapp_client_http($url);
// if ($client->errors)
// {
// array_push($this->errors, ...$client->errors);
// }
// return $this($client->headers(['User-Agent' => 'WebApp/' . self::version]));
}
function cond(...$conditionals):object
{
return new class($this->query, ...$conditionals)
{
private array $syntax = [], $values = [], $merge = [];
function __construct(private readonly array $query, ...$conditionals)
{
$this->append(...$conditionals);
}
function __invoke(callable $object):object
{
$syntax = join(' AND ', $this->syntax);
if ($syntax && $object instanceof webapp_mysql_table)
{
$syntax = "WHERE {$syntax} ";
}
if ($this->merge)
{
$syntax .= join(',', $this->merge);
}
return $syntax ? $object($syntax, ...$this->values) : $object;
}
function query(string $name, string $syntax, callable $format = NULL, string $default = NULL):?string
{
if (is_string($value = $this->query[$name] ?? $default))
{
$this->syntax[] = $syntax;
$this->values[] = is_callable($format) ? $format($value) : $value;
return $value;
}
return NULL;
}
function append(...$conditionals):void
{
if ($conditionals)
{
$this->syntax[] = array_shift($conditionals);
array_push($this->values, ...$conditionals);
}
}
function merge(string $conditionals):void
{
$this->merge[] = $conditionals;
}
};
}
//function sqlite():webapp_sqlite{}
function mysql(...$commands):webapp_mysql
{
if ($commands)
{
return ($this->mysql)(...$commands);
}
if (property_exists($this, 'mysql'))
{
return $this->mysql;
}
$mysql = new webapp_mysql($this['mysql_hostname'], $this['mysql_username'], $this['mysql_password'], $this['mysql_database'], $this['mysql_maptable']);
if ($mysql->connect_errno)
{
$this->errors[] = $mysql->connect_error;
}
else
{
$mysql->set_charset($this['mysql_charset']);
}
return $this($mysql);
}
function redis():webapp_redis
{
$redis = new webapp_redis($this, ...$this['redis_open']);
$this['redis_auth'] && $redis->auth($this['redis_auth']);
return $this($redis);
}
//request
function request_header(string $name):?string
{
return $this->io->request_header($name);
}
function request_ip():string
{
//CF-Connecting-IP
return is_string($ip = $this->request_header('X-Forwarded-For'))
? current(explode(',', $ip))
: $this->io->request_ip();
}
function request_country():?string
{
//CF-IPCountry
return $this->request_header('CF-IPCountry') ?? NULL;
}
function request_time():int
{
return $this->io->request_time();
}
function request_scheme():string
{
return $this->request_header('X-Forwarded-Proto')
?? $this->io->request_scheme();
}
function request_host():string
{
return $this->request_header('X-Forwarded-Host')
?? $this->request_header('Host')
?? $this->request_ip();
}
function request_origin(string $path = NULL):string
{
return sprintf('%s://%s%s', $this->request_scheme(), $this->request_host(), $path);
}
function request_authorization(&$type = NULL):?string
{
return is_string($authorization = $this->request_header('Authorization'))
? ([$type] = explode(' ', $authorization, 2))[1] ?? $type : NULL;
}
function request_sign_in():array
{
return [parse_str($this->request_header('Sign-In') ?? '', $result), $result][1];
}
function request_cookie(string $name):?string
{
return $this->io->request_cookie($name);
}
function request_cookie_decrypt(string $name):?string
{
return static::decrypt($this->request_cookie($name));
}
function request_device():string
{
return $this->request_header('User-Agent') ?? 'Unknown';
}
function request_referer(string $url):string
{
return $this->request_header('Referer') ?? $url;
}
function request_content_type():string
{
return is_string($type = $this->request_header('Content-Type'))
? strtolower(is_int($offset = strpos($type, ';')) ? substr($type, 0, $offset) : $type)
: 'application/octet-stream';
}
function request_content_length():int
{
return intval($this->request_header('Content-Length'));
}
function request_content(?string $format = NULL):array|string|webapp_xml
{
// if (in_array($format ??= $this->request_content_type(), ['application/x-www-form-urlencoded', 'multipart/form-data']))
// {
// return $this->io->request_formdata();
// }
// $content = is_string($key = $this->request_header('Mask-Key'))
// ? $this->unmasker(hex2bin($key), $this->io->request_content())
// : $this->io->request_content();
// return match ($format)
// {
// 'application/json' => json_decode($content, TRUE),
// 'application/xml' => static::xml($content),
// default => $content
// };
// $content = is_string($key = $this->request_header('Mask-Key'))
// ? $this->unmasker(hex2bin($key), $this->io->request_content())
// :
return match ($format ?? $this->request_content_type())
{
'application/x-www-form-urlencoded',
'multipart/form-data' => $this->io->request_formdata(),
'application/json' => json_decode($this->io->request_content(), TRUE),
'application/xml' => static::xml($this->io->request_content()),
default => $this->io->request_content()
};
}
function request_uploadedfile(string $name, ?int $maximum = 1, int $maxpathdeep = 0):webapp_request_uploadedfile
{
static $uploadedfile = $this->io->request_uploadedfile();
return $this->uploadedfiles[$name] ??= new webapp_request_uploadedfile($this, $name, $uploadedfile, $maximum, $maxpathdeep);
}
// function request_cond(string $name = 'cond'):array
// {
// $cond = [];
// preg_match_all('/(\w+\.(?:eq|ne|gt|ge|lt|le|lk|nl|in|ni))(?:\.([^\/]*))?/', $this->request_query($name), $values, PREG_SET_ORDER);
// foreach ($values as $value)
// {
// $cond[$value[1]] = array_key_exists(2, $value) ? urldecode($value[2]) : NULL;
// }
// return $cond;
// }
// function request_apple_device_enrollment():array
// {
// //Apple device enrollment must use HTTPS protocol request method POST and response status 301
// return preg_match_all('/\<(\w+\>)([^\<]+)\<\/\1\s*\<(\w+\>)([^\<]+)\<\/\3/',
// $this->request_content('application/pkcs7-signature'), $pattern)
// ? array_combine($pattern[2], $pattern[4]) : [];
// }
//response
function response_status(int $code):void
{
$this->break(fn():int => $code);
}
function response_cookie(string $name, ?string $value = NULL, int $expire = 0, string $path = '', string $domain = '', bool $secure = FALSE, bool $httponly = FALSE):void
{
$cookie = func_get_args();
$cookie[1] ??= '';
$this->cookies[] = $cookie;
}
function response_cookie_encrypt(string $name, ?string $value = NULL, int $expire = 0, string $path = '', string $domain = '', bool $secure = FALSE, bool $httponly = FALSE):void
{
$cookie = func_get_args();
$cookie[1] = static::encrypt($value) ?? '';
$this->cookies[] = $cookie;
}
function response_header(string $name, string $value):void
{
$this->headers[$name] = $value;
}
function response_location(string $url):void
{
$this->response_header('Location', $url);
}
function response_refresh(int $second = 0, string $url = NULL):void
{
$this->response_header('Refresh', $url === NULL ? (string)$second : "{$second}; url={$url}");
}
function response_expires(int $timestamp):void
{
$this->response_header('Expires', date(DateTimeInterface::RFC7231, $timestamp));
}
function response_last_modified(int $timestamp):void
{
$this->response_header('Last-Modified', date(DateTimeInterface::RFC7231, $timestamp));
}
function response_cache_control(string $command):void
{
$this->response_header('Cache-Control', $command);
}
function response_content_type(string $mime):void
{
$this->response_header('Content-Type', $mime);
}
function response_content_disposition(string $basename):void
{
$this->response_header('Content-Disposition', 'attachment; filename=' . urlencode($basename));
}
function response_content_download(string $basename):void
{