-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.php
2032 lines (1747 loc) · 60.6 KB
/
core.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
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
namespace ThreadFin\File;
use ThreadFin\Core\TF_Error;
use function ThreadFin\Log\debug;
use function ThreadFin\Log\trace2;
use function ThreadFin\Util\dbg;
require __DIR__ . "/storage.php";
const FILE_RW = 0664;
const FILE_R = 0444;
/**
* a file modification class to define a change to the file system
*/
class FileChange {
public function __construct(
public readonly string $filename,
public readonly string $content,
public readonly int $write_mode = 0,
public readonly int $mod_time = 0,
public readonly bool $append = false) {
assert(!empty($filename), "File Change has empty filename");
assert(in_array($write_mode, [0644, 0664, 0666, 0775, 0444, 0400, 0000]), "File Permissions must be 0644, 0664, 0666, 0775, 0444, or 0400");
}
}
/**
* write a file-change to the file system
* @param FileChange $file
* @return null|TF_Error
*/
function writer(FileChange $file) : ?TF_Error {
assert(!empty($file->filename), "can't write to null file: " . json_encode($file));
trace2("WFile");
$len = strlen($file->content);
debug("FS(w) [%s] (%d)bytes", $file->filename, $len);
// create the path if we need to
$dir = dirname($file->filename);
if (!file_exists($dir)) {
// echo "mkdir ($dir)\n";
if (!mkdir($dir, 0755, true)) {
return new TF_Error("unable to mkdir -r [$dir]", __FILE__, __LINE__);
}
}
// ensure write-ability
$perm = -1;
if (file_exists($file->filename)) {
if (!is_writeable($file->filename)) {
$st = stat($file->filename);
$perm = $st["mode"];
if (!chmod($file->filename, FILE_RW)) {
$name = basename($file->filename);
return new TF_Error("unable to make file writeable [$name]", __FILE__, __LINE__);
}
}
}
// write the file content
$mods = ($file->append) ? FILE_APPEND : LOCK_EX;
$written = file_put_contents($file->filename, $file->content, $mods);
if ($written != $len) {
$e = error_get_last();
return new TF_Error("failed to write file: $file->filename " . strlen($file->content) . " bytes. " . json_encode($e), __FILE__, __LINE__);
}
// update file permissions
if ($file->write_mode > 0) {
if (!chmod($file->filename, $file->write_mode)) {
return new TF_Error("unable to chmod {$file->filename} perm: " . $file->write_mode, __FILE__, __LINE__);
}
}
// restore file permissions if we changed them
else if ($perm != -1) {
if (!chmod($file->filename, $perm)) {
return new TF_Error("unable to restore chmod: {$file->filename} perm: {$perm}", __FILE__, __LINE__);
}
}
// update the file modification time
if ($file->mod_time > 0) {
if (!touch($file->filename, $file->mod_time)) {
return new TF_Error("unable to set {$file->filename} mod_time to: " . $file->mod_time, __FILE__, __LINE__);
}
}
return NULL;
}
namespace ThreadFin\Log;
if (!defined("ThreadFin\Log\TRACE_LEVEL")) {
define("ThreadFin\Log\TRACE_LEVEL", 1);
}
const RETURN_LOG = -99;
const CLEAN_LOG = -101;
const ACTION_RETURN = -9999999;
const ACTION_CLEAN = -9999998;
function trace1(string $marker, int $stacktrace_level = 0) : void {
if (TRACE_LEVEL < 1) { return; }
trace(1, $marker, $stacktrace_level);
}
function trace2(string $marker, int $stacktrace_level = 0) : void {
if (TRACE_LEVEL < 2) { return; }
trace(2, $marker, $stacktrace_level);
}
function trace3(string $marker, int $stacktrace_level = 0) : void {
if (TRACE_LEVEL < 3) { return; }
trace(3, $marker, $stacktrace_level);
}
/**
* add a marker to the TRACE LOG. if level === TRACE_RETURN_LOG, the trace log will be returned
* be returned
* @param int $level - the message log level.
* @param string $marker - a short marker for the trace log
* @param int $stacktrace_level - display a file and line number from this many stack frames ago (+1 for this function)
* @return void
*/
function trace(int $level, string $marker = "", int $stacktrace_level = 0) : ?string {
static $markers = "";
// return the trace log if we're done
if ($level === RETURN_LOG) {
return $markers;
}
assert(strlen($marker) > 0 && strlen($marker) < 16, "trace markers must be between 1 and 16 characters long. [$marker]");
if ($stacktrace_level > 0) {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $stacktrace_level + 1);
$file = basename($trace[$stacktrace_level+1]['file']);
$line = intval($trace[$stacktrace_level+1]['line']);
$marker .= "($file:$line)";
}
$markers .= "$marker, ";
return NULL;
}
/**
* ensure that a format string has the correct number of arguments
* called from assert
* @param null|string $fmt
* @param int $args
* @return bool
*/
function format_chk(?string $fmt, int $args) : bool {
if ($fmt == null) { return true; }
return(substr_count($fmt, "%") === $args);
}
/**
* debug log can be disabled by un-defining LOG_DEBUG_ENABLE
* add a line to the debug log, immediately output a header if LOG_DEBUG_HEADER is defined
*/
function debug(?string $fmt, ...$args) : ?array {
assert(format_chk($fmt, count($args)), "programmer error, format string does not match number of arguments [$fmt]");
static $idx = 0;
static $len = 0;
static $log = [];
if (!defined('LOG_DEBUG_ENABLE')) { return null;}
if (empty($fmt)) { return $log; } // retrieve log lines
$fmt = str_replace(array("\r","\n"), array(" "," "), $fmt);
foreach ($args as &$arg) { if (is_array($arg)) { $arg = json_encode($arg, JSON_PRETTY_PRINT); } }
$line = sprintf($fmt, ...$args);
$log[] = $line;
// directly write to the header line
if (defined('LOG_DEBUG_HEADER')) {
if (!headers_sent() && $idx < 24) {
$line = str_replace(array("\r","\n",":"), array(" "," ",";"), $line);
$s = sprintf("x-log-%02d: %s", $idx, substr($line, 0, 1024));
$len += strlen($s);
if ($len < 2048-1) {
header($s);
}
$idx++;
}
}
file_put_contents(LOG_PATH, "$line\n", FILE_APPEND | LOCK_EX);
return null;
}
/**
* register the path to write the debug log to on shutdown
* @param string $path
* @return void
*/
function debug_log_file(string $path, bool $immediate = false) : void {
if (!defined('LOG_DEBUG_ENABLE')) {
define ("LOG_DEBUG_ENABLE", true);
}
define("LOG_IMMEDIATE", $immediate);
define("LOG_PATH", $path);
if (LOG_DEBUG_ENABLE) {
if (!$immediate) {
register_shutdown_function(function() use ($path) {
$log = debug(null);
if (empty($log)) { return; }
$log = implode("\n", $log);
file_put_contents($path, "$log\n", FILE_APPEND);
});
}
}
}
namespace ThreadFin\Core;
use InvalidArgumentException;
use OutOfBoundsException;
use ReturnTypeWillChange;
use ThreadFin\File\FileChange;
use const ThreadFin\DAY;
use const ThreadFin\Log\RETURN_LOG;
use function ThreadFin\Assertions\fn_arg_x_has_type;
use function ThreadFin\Assertions\fn_arg_x_is_type;
use function ThreadFin\Assertions\fn_returns_type;
use function ThreadFin\Assertions\fn_takes_x_args;
use function ThreadFin\Assertions\fn_takes_x_or_more_args;
use function ThreadFin\Assertions\last_assert_err;
use function ThreadFin\Log\debug;
use function ThreadFin\Log\trace;
use function ThreadFin\Log\trace2;
use function ThreadFin\Log\trace3;
use function ThreadFin\Util\array_clone;
use function ThreadFin\Util\func_name;
/**
* a root class all of our classes
* @package ThreadFin
*/
class Entity {
}
interface Hash_Code {
public function hash_code() : string;
}
/**
* a <generic> list. this is the base class for all typed lists
* @package ThreadFin\Core
*/
abstract class Typed_List implements \ArrayAccess, \Iterator, \Countable, \SeekableIterator {
protected string $_type = "mixed";
protected $_position = 0;
protected array $_list;
private bool $_is_associated = false;
private $_keys;
public function __construct(array $list = []) {
$this->_list = $list;
$this->_type = $this->get_type();
}
/**
* Example: echo $list[$index]
* @param mixed $index index may be numeric or hash key
* @return $this->_type cast this to your subclass type
*/
#[\ReturnTypeWillChange]
public abstract function offsetGet(mixed $index): mixed;
/**
* Example: foreach ($list as $key => $value)
* @return mixed cast this to your subclass type at the current iterator index
*/
#[\ReturnTypeWillChange]
public abstract function current(): mixed;
/**
* @return string the name of the type list supports or mixed
*/
public abstract function get_type() : string;
/**
* return a new instance of the subclass with the given list
* @param array $list
* @return static
*/
public static function of(array $list) : static {
return new static($list);
}
/**
* clone the current list into a new object
* @return static new instance of subclass
*/
#[\ReturnTypeWillChange]
public function clone() {
$new = new static();
$new->_list = array_clone($this->_list);
return $new;
}
/**
* Example count($list);
* @return int<0, \max> - the number of elements in the list
*/
public function count(): int {
return count($this->_list);
}
/**
* SeekableIterator implementation
* @param mixed $position - seek to this position in the list
* @throws OutOfBoundsException - if the element does not exist
*/
public function seek($position) : void {
if (!isset($this->_list[$position])) {
throw new OutOfBoundsException("invalid seek position ($position)");
}
$this->_position = $position;
}
/**
* SeekableIterator implementation. seek internal pointer to the first element
* @param mixed $position - seek to this position in the list
*/
public function rewind() : void {
if ($this->_is_associated) {
$this->_keys = array_keys($this->_list);
$this->_position = array_shift($this->_keys);
} else {
$this->_position = 0;
}
}
/**
* SeekableIterator implementation. equivalent of calling current()
* @return mixed - the pointer to the current element
*/
public function key() : mixed {
return $this->_position;
}
/**
* SeekableIterator implementation. equivalent of calling next()
*/
public function next(): void {
if ($this->_is_associated) {
$this->_position = array_shift($this->_keys);
} else {
++$this->_position;
}
}
/**
* SeekableIterator implementation. check if the current position is valid
*/
public function valid() : bool {
if (isset($this->_list[$this->_position])) {
if ($this->_type != "mixed") {
return $this->_list[$this->_position] instanceof $this->_type;
}
return true;
}
return false;
}
/**
* Example: $list[1] = "data"; $list[] = "data2";
* ArrayAccess implementation. set the value at a specific index
* @throws
*/
public function offsetSet($index, $value) : void {
// type checking
if ($this->_type != "mixed") {
if (! $value instanceof $this->_type) {
$msg = get_class($this) . " only accepts objects of type \"" . $this->_type . "\", \"" . gettype($value) . "\" passed";
throw new InvalidArgumentException($msg, 1);
}
}
if (empty($index)) {
$this->_list[] = $value;
} else {
$this->_is_associated = true;
if ($index instanceof Hash_Code) {
$this->_list[$index->hash_code()] = $value;
} else {
$this->_list[$index] = $value;
}
}
}
/**
* unset($list[$value]);
* ArrayAccess implementation. unset the value at a specific index
*/
public function offsetUnset($index) : void {
unset($this->_list[$index]);
}
/**
* ArrayAccess implementation. check if the value at a specific index exist
*/
public function offsetExists($index) : bool {
return isset($this->_list[$index]);
}
/**
* example $data = array_map($fn, $list->raw());
* @return array - the internal array structure
*/
public function &raw() : array {
return $this->_list;
}
/**
* sort the list
* @return static - the current instance sorted
*/
public function ksort(int $flags = SORT_REGULAR): static {
ksort($this->_list, $flags);
return $this;
}
/**
* @return bool - true if the list is empty
*/
public function empty() : bool {
return empty($this->_list);
}
/**
* helper method to be used by offsetGet() and current(), does bounds and key type checking
* @param mixed $key
* @throws OutOfBoundsException - if the key is out of bounds
*/
protected function protected_get($key) {
if ($this->_is_associated) {
if (isset($this->_list[$key])) {
return $this->_list[$key];
}
}
else {
if ($key <= count($this->_list)) {
return $this->_list[$key];
}
}
throw new OutOfBoundsException("invalid key [$key]");
}
/**
* filter the list using the given function
* @param callable $fn
* @return static
*/
public function filter(callable $fn, bool $clone = false) {
assert(fn_takes_x_args($fn, 1), last_assert_err() . " in " . get_class($this) . "->map()");
assert(fn_arg_x_is_type($fn, 0, $this->_type), last_assert_err() . " in " . get_class($this) . "->map()");
if ($clone) {
return new static(array_filter(array_clone($this->_list), $fn));
}
$this->_list = array_filter($this->_list, $fn);
return $this;
}
/**
* json encoded version of the list
* @return string json encoded version of first 5 elements
*/
public function __toString() : string {
return json_encode(array_slice($this->_list, 0, 5));
}
}
/**
* generic error type. can be used for anything
* @package ThreadFin
*/
class TF_Error {
public function __construct(
public readonly string $message,
public readonly string $file,
public readonly int $line,
) { }
}
/**
* a <generic> list of errors
* @package
*/
class TF_ErrorList extends Typed_List {
public function get_type() : string { return "\ThreadFin\Core\TF_Error"; }
// used for index access
public function offsetGet($index): ?TF_Error {
return $this->_list[$index] ?? null;
}
// used by foreach
public function current(): ?TF_Error {
return $this->_list[$this->_position] ?? null;
}
/**
* add a new error to the list
* @param null|TF_Error $error
*/
public function add(?TF_Error $error) : void {
if (!empty($error)) {
$this->_list[] = $error;
}
}
}
/**
* define a single cache entry
*/
class CacheItem {
/**
* @param string $key - the cache key to store/update.
* if user-data is in the key, be sure to filter/limit it before passing here
* @param callable $generator_fn - function to update the value
* @param callable $init_fn - function to initialize the value
* @param int $ttl - the number of seconds to expire the cache item
* @return void
*/
public function __construct(
public readonly string $key,
public readonly string $generator_fn,
public readonly string $init_fn,
public readonly int $ttl) {
assert($ttl > 0, "Cache TTL must be > 0. Clear entry by returning NULL from generator_fn");
assert($ttl < 86400*30, "Cache TTL must be < 30 days");
assert(strlen($key) > 4, "Cache key length must be > 4 characters");
assert(strlen($key) < 96, "Cache key length must be < 96 characters");
assert(function_exists((string)$generator_fn), "Cache generator_fn must be a valid function");
assert(function_exists((string)$init_fn), "Cache init_fn must be a valid function");
}
}
/**
* result from a REST API call
* @package ThreadFin
*/
class ApiResult {
public array $errors;
public function __construct(
public bool $success,
public readonly string $note,
public readonly array $result = [],
public readonly int $status_code = 0
) {
assert(!empty($note), "ApiResult note cannot be empty");
}
}
/**
* an HTTP cookie
* @package ThreadFin
*/
class Cookie {
public function __construct(
public readonly string $name,
public readonly string $value,
public readonly int $expires = 0,
public readonly string $path = "/",
public readonly string $domain = "",
public readonly bool $secure = true,
public readonly bool $http_only = true
) {
assert(!empty($name), "cookie name may not be null");
}
}
/**
* The status of an effect. Each effect generator will have it's
* own meaning for each status. Add more statuses as needed.
* Lets keep the number of status < 2 dozen
*/
enum EffectStatus {
case OK;
case FAIL;
}
/**
* abstract away external effects
*/
class Effect {
protected static ?string $runner = null;
const ENCODE_RAW = 0;
const ENCODE_HTML = 1;
const ENCODE_BASE64 = 2;
const ENCODE_SPECIAL = 3;
private EffectStatus $status;
private ?ApiResult $api_result = null;
private string $out = '';
private int $response = 0;
private bool $exit = false;
public bool $hide_output = false;
// we don't define internal arrays until they are used (to save memory)
private array $headers;
private array $cookies;
private array $cache;
private array $file_outs;
private array $unlinks;
protected function __construct() {
$this->status = EffectStatus::OK;
}
// $fn is the effect runner to use. must take an Effect and return a TF_ErrorList
// THIS IS GLOBAL TO ALL INSTANCES OF EFFECT
public static function set_runner(callable $fn) : void {
assert(fn_returns_type($fn, "ThreadFin\Core\TF_ErrorList"), "Effect runner " . last_assert_err());
assert(fn_arg_x_is_type($fn, 0, "ThreadFin\Core\Effect"), "Effect runner " . last_assert_err());
assert(self::$runner === null, "Effect Runner can only be set 1x");
self::$runner = $fn;
}
/**
* create a new empty effect
* @return Effect
*/
public static function new() : Effect {
assert(func_num_args() == 0, "incorrect call of Effect::new()");
return new Effect();
}
/**
* run this effect with the GLOBAL effect runner
* @return TF_ErrorList
*/
public function run() : TF_ErrorList {
assert(!empty(self::$runner), "Effect runner not set");
$fn = self::$runner;
return $fn($this);
}
/**
* add request output to the effect.
* @param string $content - the content to add
* @param int $encoding - optional encoding to apply to content
* @param bool $replace - if true any previous content will be replaced
* @return Effect
*/
public function out(string $content, int $encoding = Effect::ENCODE_RAW, bool $replace = false) : Effect {
trace3("OUT", 1);
$tmp = match ($encoding) {
Effect::ENCODE_SPECIAL => htmlspecialchars($content),
Effect::ENCODE_HTML => htmlentities($content),
Effect::ENCODE_BASE64 => base64_encode($content),
default => $tmp = $content
};
if ($replace) { $this->out = $tmp; }
else { $this->out .= $tmp; }
return $this;
}
/**
* add a header to the effect
* @return Effect
*/
public function header(string $name, ?string $value) : Effect {
trace3("HEADER", 1);
if (!isset($this->headers)) {
$this->headers = [];
}
$this->headers[$name] = $value;
return $this;
}
/**
* add a cookie to the effect
* @return Effect
*/
public function cookie(Cookie $cookie) : Effect {
trace3("COOKIE", 1);
if (!isset($this->cookies)) {
$this->cookies = [];
}
$this->cookies[$cookie->name] = $cookie;
return $this;
}
/**
* set the effect's HTTP response code
* @param int $code
* @return Effect
*/
public function response_code(int $code) : Effect {
trace2("HTTP_CODE", 0);
$this->response = $code;
return $this;
}
/**
* set an internal effect status code that can be read by callers
* @param EffectStatus $status a status code set by the generating function
* @return Effect
*/
public function status(EffectStatus $status) : Effect {
$this->status = $status;
return $this;
}
/**
* if set to true, the effect will cause the script to exit
* @param bool $should_exit
* @return Effect
*/
public function exit(bool $should_exit = true) : Effect {
$this->exit = $should_exit;
return $this;
}
/**
* add a file modification to the effect. existing FileChanges
* for the same file are overwritten
* @param FileChange $change
* @return Effect
*/
public function file(FileChange $change) : Effect {
$this->file_outs[$change->filename] = $change;
return $this;
}
/**
* add a cache update/create item to the effect. duplicate cache keys
* are overwritten
}
/**
* @param ApiResult $result a REST api result to return to the client
* @return Effect
*/
public function api(ApiResult $result) : Effect {
$this->api_result = $result;
return $this;
}
/**
* add file to the list to be deleted. assert error if file does not exist
* @param string $filename
* @return Effect
*/
public function unlink(string $filename) : Effect {
assert(file_exists($filename), "unlinking non-existent file: $filename");
if (!isset($this->unlinks)) {
$this->unlinks = [];
}
$this->unlinks[] = $filename;
return $this;
}
/**
* if set to true, the effect runner will not display any output
* @param bool $hide
* @return Effect
*/
public function hide_output(bool $hide = true) : Effect {
$this->hide_output = $hide;
return $this;
}
/**
* chain an effect to this one.
* Boolean values are set to the new effect
* array values are merged, newer values overwriting
* @param Effect $effect
* @param bool $append_out if true, the output of the chained effect will be appended to the output of this effect
* @return Effect
*/
public function chain(Effect $effect, bool $append_out = true) : Effect {
$this->out = ($append_out) ? $this->out . $effect->read_out() : $effect->read_out();
$this->response = $this->set_if_default('response', $effect->read_response_code(), 0);
$this->status = $this->set_if_default('status', $effect->read_status(), EffectStatus::OK);
$this->exit = $this->set_if_default('exit', $effect->read_exit(), false);
$this->set_if_default('headers', $effect->read_headers(), [], true);
$this->set_if_default('cache', $effect->read_cache(), []);
$this->set_if_default('file_outs', $effect->read_files(), []);
$this->set_if_default('cookies', $effect->read_cookies(), []);
$this->set_if_default('api', $effect->read_api(), [], true);
$this->set_if_default('unlinks', $effect->read_unlinks(), []);
return $this;
}
// helper function for effect chaining
protected function set_if_default($pname, $value, $default, $hash = false) {
if (is_array($this->$pname) && !empty($value)) {
if (is_array($value)) {
$this->$pname = array_merge($this->$pname, $value);
} else {
$this->$pname[] = $value;
}
}
else if (!empty($value) && $this->$pname === $default) { return $value; }
return $this->$pname;
}
// return true if the effect will exit
public function read_exit() : bool { return $this->exit; }
// return the effect content, if clear is true, the output
// will be returned and cleared from the effect
public function read_out(bool $clear = false) : string {
$t = $this->out;
if ($clear) {
$this->out = "";
}
return $t;
}
// return the effect headers
public function read_headers() : array { return $this->headers??[]; }
// return the effect cookie (only 1 cookie supported)
public function read_cookies() : array { return $this->cookies??[]; }
// return the effect cache updates
public function read_cache() : array { return $this->cache??[]; }
// return the effect response code
public function read_response_code() : int { return $this->response; }
// return the effect function status code
public function read_status() : EffectStatus { return $this->status; }
// return the effect filesystem changes
public function read_files() : array { return $this->file_outs??[]; }
// return the API result output
public function read_api() : ?ApiResult { return $this->api_result; }
// return the list of files to unlink
public function read_unlinks() : array { return $this->unlinks??[]; }
}
class Runner {
static $fn = null;
// $fn is the effect runner to use. must take an Effect and return a TF_ErrorList
public static function set(callable $fn) {
assert(fn_returns_type($fn, "TF_ErrorList"), "Effect runner must return a TF_ErrorList");
assert(fn_arg_x_is_type($fn, 1, "Effect"), "Effect runner must take an Effect");
self::$fn = $fn;
}
// run an effect and return the errors (if any)
public static function run(Effect $effect) : TF_ErrorList {
$f = self::$fn;
assert($f !== null, "Effect runner not set, please call Runner::set()");
return $f($effect);
}
}
/**
* set a cookie. Only works for PHP > 7.0.3
* @param string $name cookie name
* @param string $value cookie value
* @param int $exp expiration time in seconds, if negative, cookie will be removed
* @return ?TF_Error
*/
function TF_cookie(string $name, string $value, int $exp = DAY * 365, string $path = "/", string $domain = "", bool $secure = false, bool $httponly = true) : ?TF_Error {
if (headers_sent($file, $line)) {
return new TF_Error("unable to set cookie, headers already sent", $file, $line);
}
$success = setcookie($name, $value, [
'expires' => time() + $exp,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => 'strict'
]);
return ($success) ? NULL : new TF_Error("unable to set cookie", __FILE__, __LINE__-8);
}
/**
* send an http header if the headers have not been sent
* @param string $name
* @param null|string $value
* @return null|TF_Error
*/
function TF_header(string $name, ?string $value = null) : ?TF_Error {
if (headers_sent($file, $line)) {
return new TF_Error("unable to set header, headers already sent", $file, $line);
}
if ($value == null) {
header($name);
} else {
header("$name: $value");
}
return NULL;
}
// TODO: monitor runner for failures and log/report them
function effect_run(Effect $effect) : TF_ErrorList {
$errors = new TF_ErrorList();
// http response
if ($effect->read_response_code() > 0) {
http_response_code($effect->read_response_code());
}
// send all cookies
$cookies = $effect->read_cookies();
array_walk($cookies, fn(Cookie $x) =>
$errors->add(TF_cookie($x->name, $x->value, $x->expires, $x->path, $x->domain, $x->secure, $x->http_only))
);
// send all headers, map value,key to key,value
$headers = $effect->read_headers();
array_walk($headers, fn(?string $value, string $key) =>
$errors->add(TF_header($key, $value))
);
// update all cache entries
/*
TODO: add caching...
$cache = $effect->read_cache();
array_walk($cache, function(CacheItem $item) use (&$errors){
$updated = Cache::update_data(
$item->key, $item->generator_fn, $item->init_fn, $item->ttl);
if ($updated === NULL) {
$errors->add(new TF_Error("unable to update cache entry: $item->key", __FILE__, __LINE__));
}
});
*/
// write the files to disk
$files = $effect->read_files();
array_walk($files, 'ThreadFin\File\writer');
// delete all file unlinks, track any errors
$unlinks = $effect->read_unlinks();
array_walk($unlinks, function ($x) use (&$errors) {
if (!unlink($x)) {
$errors->add(new TF_Error("unable to delete file: $x", __FILE__, __LINE__));
}
});
// output api and error data if we are not set to hide it
if (!$effect->hide_output) {
// API output, force JSON content-type
$api = $effect->read_api();
if (!empty($api)) {
TF_header("content-type", "application/json");
echo json_encode($effect->read_api(), JSON_PRETTY_PRINT);
}
// standard output
else {
echo $effect->read_out();
}
}
// log any errors
if (!$errors->empty()) {
debug("ERROR effect: " . json_encode($errors, JSON_PRETTY_PRINT));
}
// exit if we are set to exit
if ($effect->read_exit()) {
debug((string)trace(RETURN_LOG, ""));
exit();
}
// we didn't exit, so return any errors
return $errors;
}
/**
* FileSystem monad abstraction
* TODO: move to ThreadFin\File
* @package ThreadFin
*/
class FileData {
public string $filename;