-
Notifications
You must be signed in to change notification settings - Fork 89
/
base.php
3644 lines (3487 loc) · 91.9 KB
/
base.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
/*
Copyright (c) 2009-2023 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or later.
Fat-Free Framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Factory class for single-instance objects
abstract class Prefab {
/**
* Return class instance
* @return static
**/
static function instance() {
if (!Registry::exists($class=get_called_class())) {
$ref=new ReflectionClass($class);
$args=func_get_args();
Registry::set($class,
$args?$ref->newinstanceargs($args):new $class);
}
return Registry::get($class);
}
}
//! Base structure
final class Base extends Prefab implements ArrayAccess {
//@{ Framework details
const
PACKAGE='Fat-Free Framework',
VERSION='3.8.2-Release';
//@}
//@{ HTTP status codes (RFC 2616)
const
HTTP_100='Continue',
HTTP_101='Switching Protocols',
HTTP_103='Early Hints',
HTTP_200='OK',
HTTP_201='Created',
HTTP_202='Accepted',
HTTP_203='Non-Authorative Information',
HTTP_204='No Content',
HTTP_205='Reset Content',
HTTP_206='Partial Content',
HTTP_300='Multiple Choices',
HTTP_301='Moved Permanently',
HTTP_302='Found',
HTTP_303='See Other',
HTTP_304='Not Modified',
HTTP_305='Use Proxy',
HTTP_307='Temporary Redirect',
HTTP_308='Permanent Redirect',
HTTP_400='Bad Request',
HTTP_401='Unauthorized',
HTTP_402='Payment Required',
HTTP_403='Forbidden',
HTTP_404='Not Found',
HTTP_405='Method Not Allowed',
HTTP_406='Not Acceptable',
HTTP_407='Proxy Authentication Required',
HTTP_408='Request Timeout',
HTTP_409='Conflict',
HTTP_410='Gone',
HTTP_411='Length Required',
HTTP_412='Precondition Failed',
HTTP_413='Request Entity Too Large',
HTTP_414='Request-URI Too Long',
HTTP_415='Unsupported Media Type',
HTTP_416='Requested Range Not Satisfiable',
HTTP_417='Expectation Failed',
HTTP_421='Misdirected Request',
HTTP_422='Unprocessable Entity',
HTTP_423='Locked',
HTTP_429='Too Many Requests',
HTTP_451='Unavailable For Legal Reasons',
HTTP_500='Internal Server Error',
HTTP_501='Not Implemented',
HTTP_502='Bad Gateway',
HTTP_503='Service Unavailable',
HTTP_504='Gateway Timeout',
HTTP_505='HTTP Version Not Supported',
HTTP_507='Insufficient Storage',
HTTP_511='Network Authentication Required';
//@}
const
//! Mapped PHP globals
GLOBALS='GET|POST|COOKIE|REQUEST|SESSION|FILES|SERVER|ENV',
//! HTTP verbs
VERBS='GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS',
//! Default directory permissions
MODE=0755,
//! Syntax highlighting stylesheet
CSS='code.css';
//@{ Request types
const
REQ_SYNC=1,
REQ_AJAX=2,
REQ_CLI=4;
//@}
//@{ Error messages
const
E_Pattern='Invalid routing pattern: %s',
E_Named='Named route does not exist: %s',
E_Alias='Invalid named route alias: %s',
E_Fatal='Fatal error: %s',
E_Open='Unable to open %s',
E_Routes='No routes specified',
E_Class='Invalid class %s',
E_Method='Invalid method %s',
E_Hive='Invalid hive key %s';
//@}
private
//! Globals
$hive,
//! Initial settings
$init,
//! Language lookup sequence
$languages,
//! Mutex locks
$locks=[],
//! Default fallback language
$fallback='en';
/**
* Sync PHP global with corresponding hive key
* @return array
* @param $key string
**/
function sync($key) {
return $this->hive[$key]=&$GLOBALS['_'.$key];
}
/**
* Return the parts of specified hive key
* @return array
* @param $key string
**/
private function cut($key) {
return preg_split('/\[\h*[\'"]?(.+?)[\'"]?\h*\]|(->)|\./',
$key,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
}
/**
* Replace tokenized URL with available token values
* @return string
* @param $url array|string
* @param $addParams boolean merge default PARAMS from hive into args
* @param $args array
**/
function build($url, $args=[], $addParams=TRUE) {
if ($addParams)
$args+=$this->recursive($this->hive['PARAMS'], function($val) {
return implode('/', array_map('urlencode', explode('/', $val)));
});
if (is_array($url))
foreach ($url as &$var) {
$var=$this->build($var,$args, false);
unset($var);
}
else {
$i=0;
$url=preg_replace_callback('/(\{)?@(\w+)(?(1)\})|(\*)/',
function($match) use(&$i,$args) {
if (isset($match[2]) &&
array_key_exists($match[2],$args))
return $args[$match[2]];
if (isset($match[3]) &&
array_key_exists($match[3],$args)) {
if (!is_array($args[$match[3]]))
return $args[$match[3]];
++$i;
return $args[$match[3]][$i-1];
}
return $match[0];
},$url);
}
return $url;
}
/**
* Parse string containing key-value pairs
* @return array
* @param $str string
**/
function parse($str) {
preg_match_all('/(\w+|\*)\h*=\h*(?:\[(.+?)\]|(.+?))(?=,|$)/',
$str,$pairs,PREG_SET_ORDER);
$out=[];
foreach ($pairs as $pair)
if ($pair[2]) {
$out[$pair[1]]=[];
foreach (explode(',',$pair[2]) as $val)
array_push($out[$pair[1]],$val);
}
else
$out[$pair[1]]=trim($pair[3]);
return $out;
}
/**
* Cast string variable to PHP type or constant
* @param $val
* @return mixed
*/
function cast($val) {
if ($val && preg_match('/^(?:0x[0-9a-f]+|0[0-7]+|0b[01]+)$/i',$val))
return intval($val,0);
if (is_numeric($val))
return $val+0;
$val=trim($val?:'');
if (preg_match('/^\w+$/i',$val) && defined($val))
return constant($val);
return $val;
}
/**
* Convert JS-style token to PHP expression
* @return string
* @param $str string
* @param $evaluate bool compile expressions as well or only convert variable access
**/
function compile($str, $evaluate=TRUE) {
return (!$evaluate)
? preg_replace_callback(
'/^@(\w+)((?:\..+|\[(?:(?:[^\[\]]*|(?R))*)\])*)/',
function($expr) {
$str='$'.$expr[1];
if (isset($expr[2]))
$str.=preg_replace_callback(
'/\.([^.\[\]]+)|\[((?:[^\[\]\'"]*|(?R))*)\]/',
function($sub) {
$val=isset($sub[2]) ? $sub[2] : $sub[1];
if (ctype_digit($val))
$val=(int)$val;
$out='['.$this->export($val).']';
return $out;
},
$expr[2]
);
return $str;
},
$str
)
: preg_replace_callback(
'/(?<!\w)@(\w+(?:(?:\->|::)\w+)?)'.
'((?:\.\w+|\[(?:(?:[^\[\]]*|(?R))*)\]|(?:\->|::)\w+|\()*)/',
function($expr) {
$str='$'.$expr[1];
if (isset($expr[2]))
$str.=preg_replace_callback(
'/\.(\w+)(\()?|\[((?:[^\[\]]*|(?R))*)\]/',
function($sub) {
if (empty($sub[2])) {
if (ctype_digit($sub[1]))
$sub[1]=(int)$sub[1];
$out='['.
(isset($sub[3])?
$this->compile($sub[3]):
$this->export($sub[1])).
']';
}
else
$out=function_exists($sub[1])?
$sub[0]:
('['.$this->export($sub[1]).']'.$sub[2]);
return $out;
},
$expr[2]
);
return $str;
},
$str
);
}
/**
* Get hive key reference/contents; Add non-existent hive keys,
* array elements, and object properties by default
* @return mixed
* @param $key string
* @param $add bool
* @param $var mixed
**/
function &ref($key,$add=TRUE,&$var=NULL) {
$null=NULL;
$parts=$this->cut($key);
if ($parts[0]=='SESSION') {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
$this->sync('SESSION');
}
elseif (!preg_match('/^\w+$/',$parts[0]))
user_error(sprintf(self::E_Hive,$this->stringify($key)),
E_USER_ERROR);
if (is_null($var)) {
if ($add)
$var=&$this->hive;
else
$var=$this->hive;
}
$obj=FALSE;
foreach ($parts as $part)
if ($part=='->')
$obj=TRUE;
elseif ($obj) {
$obj=FALSE;
if (!is_object($var))
$var=new stdClass;
if ($add || property_exists($var,$part))
$var=&$var->$part;
else {
$var=&$null;
break;
}
}
else {
if (!is_array($var))
$var=[];
if ($add || array_key_exists($part,$var))
$var=&$var[$part];
else {
$var=&$null;
break;
}
}
return $var;
}
/**
* Return TRUE if hive key is set
* (or return timestamp and TTL if cached)
* @return bool
* @param $key string
* @param $val mixed
**/
function exists($key,&$val=NULL) {
$val=$this->ref($key,FALSE);
return isset($val)?
TRUE:
(Cache::instance()->exists($this->hash($key).'.var',$val)?:FALSE);
}
/**
* Return TRUE if hive key is empty and not cached
* @param $key string
* @param $val mixed
* @return bool
**/
function devoid($key,&$val=NULL) {
$val=$this->ref($key,FALSE);
return empty($val) &&
(!Cache::instance()->exists($this->hash($key).'.var',$val) ||
!$val);
}
/**
* Bind value to hive key
* @return mixed
* @param $key string
* @param $val mixed
* @param $ttl int
**/
function set($key,$val,$ttl=0) {
$time=(int)$this->hive['TIME'];
if (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
$this->set('REQUEST'.$expr[2],$val);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
$jar=$this->unserialize($this->serialize($this->hive['JAR']));
unset($jar['lifetime']);
if (version_compare(PHP_VERSION, '7.3.0') >= 0) {
unset($jar['expire']);
if (isset($_COOKIE[$parts[1]]))
setcookie($parts[1],'',['expires'=>0]+$jar);
if ($ttl)
$jar['expires']=$time+$ttl;
setcookie($parts[1],$val?:'',$jar);
} else {
unset($jar['samesite']);
if (isset($_COOKIE[$parts[1]]))
call_user_func_array('setcookie',
array_merge([$parts[1],''],['expire'=>0]+$jar));
if ($ttl)
$jar['expire']=$time+$ttl;
call_user_func_array('setcookie',[$parts[1],$val?:'']+$jar);
}
$_COOKIE[$parts[1]]=$val;
return $val;
}
}
else switch ($key) {
case 'CACHE':
$val=Cache::instance()->load($val);
break;
case 'ENCODING':
ini_set('default_charset',$val);
if (extension_loaded('mbstring'))
mb_internal_encoding($val);
break;
case 'FALLBACK':
$this->fallback=$val;
$lang=$this->language($this->hive['LANGUAGE']);
case 'LANGUAGE':
if (!isset($lang))
$val=$this->language($val);
$lex=$this->lexicon($this->hive['LOCALES'],$ttl);
case 'LOCALES':
if (isset($lex) || $lex=$this->lexicon($val,$ttl))
foreach ($lex as $dt=>$dd) {
$ref=&$this->ref($this->hive['PREFIX'].$dt);
$ref=$dd;
unset($ref);
}
break;
case 'TZ':
date_default_timezone_set($val);
break;
}
$ref=&$this->ref($key);
$ref=$val;
if (preg_match('/^JAR\b/',$key)) {
if ($key=='JAR.lifetime')
$this->set('JAR.expire',$val==0?0:
(is_int($val)?$time+$val:strtotime($val)));
else {
if ($key=='JAR.expire')
$this->hive['JAR']['lifetime']=max(0,$val-$time);
$jar=$this->unserialize($this->serialize($this->hive['JAR']));
unset($jar['expire']);
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
if (version_compare(PHP_VERSION, '7.3.0') >= 0)
session_set_cookie_params($jar);
else {
unset($jar['samesite']);
call_user_func_array('session_set_cookie_params',$jar);
}
}
}
if ($ttl)
// Persist the key-value pair
Cache::instance()->set($this->hash($key).'.var',$val,$ttl);
return $ref;
}
/**
* Retrieve contents of hive key
* @return mixed
* @param $key string
* @param $args string|array
**/
function get($key,$args=NULL) {
if (is_string($val=$this->ref($key,FALSE)) && !is_null($args))
return call_user_func_array(
[$this,'format'],
array_merge([$val],is_array($args)?$args:[$args])
);
if (is_null($val)) {
// Attempt to retrieve from cache
if (Cache::instance()->exists($this->hash($key).'.var',$data))
return $data;
}
return $val;
}
/**
* Unset hive key
* @param $key string
**/
function clear($key) {
// Normalize array literal
$cache=Cache::instance();
$parts=$this->cut($key);
if ($key=='CACHE')
// Clear cache contents
$cache->reset();
elseif (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
$this->clear('REQUEST'.$expr[2]);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
$jar=$this->hive['JAR'];
unset($jar['lifetime']);
$jar['expire']=0;
if (version_compare(PHP_VERSION, '7.3.0') >= 0) {
$jar['expires']=$jar['expire'];
unset($jar['expire']);
setcookie($parts[1],'',$jar);
} else {
unset($jar['samesite']);
call_user_func_array('setcookie',
array_merge([$parts[1],''],$jar));
}
unset($_COOKIE[$parts[1]]);
}
}
elseif ($parts[0]=='SESSION') {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
if (empty($parts[1])) {
// End session
session_unset();
session_destroy();
$this->clear('COOKIE.'.session_name());
}
$this->sync('SESSION');
}
if (!isset($parts[1]) && array_key_exists($parts[0],$this->init))
// Reset global to default value
$this->hive[$parts[0]]=$this->init[$parts[0]];
else {
$val=preg_replace('/^(\$hive)/','$this->hive',
$this->compile('@hive.'.$key, FALSE));
eval('unset('.$val.');');
if ($parts[0]=='SESSION') {
session_commit();
session_start();
}
if ($cache->exists($hash=$this->hash($key).'.var'))
// Remove from cache
$cache->clear($hash);
}
}
/**
* Return TRUE if hive variable is 'on'
* @return bool
* @param $key string
**/
function checked($key) {
$ref=&$this->ref($key);
return $ref=='on';
}
/**
* Return TRUE if property has public visibility
* @return bool
* @param $obj object
* @param $key string
**/
function visible($obj,$key) {
if (property_exists($obj,$key)) {
$ref=new ReflectionProperty(get_class($obj),$key);
$out=$ref->ispublic();
unset($ref);
return $out;
}
return FALSE;
}
/**
* Multi-variable assignment using associative array
* @param $vars array
* @param $prefix string
* @param $ttl int
**/
function mset(array $vars,$prefix='',$ttl=0) {
foreach ($vars as $key=>$val)
$this->set($prefix.$key,$val,$ttl);
}
/**
* Publish hive contents
* @return array
**/
function hive() {
return $this->hive;
}
/**
* Copy contents of hive variable to another
* @return mixed
* @param $src string
* @param $dst string
**/
function copy($src,$dst) {
$ref=&$this->ref($dst);
return $ref=$this->ref($src,FALSE);
}
/**
* Concatenate string to hive string variable
* @return string
* @param $key string
* @param $val string
**/
function concat($key,$val) {
$ref=&$this->ref($key);
$ref.=$val;
return $ref;
}
/**
* Swap keys and values of hive array variable
* @return array
* @param $key string
* @public
**/
function flip($key) {
$ref=&$this->ref($key);
return $ref=array_combine(array_values($ref),array_keys($ref));
}
/**
* Add element to the end of hive array variable
* @return mixed
* @param $key string
* @param $val mixed
**/
function push($key,$val) {
$ref=&$this->ref($key);
$ref[]=$val;
return $val;
}
/**
* Remove last element of hive array variable
* @return mixed
* @param $key string
**/
function pop($key) {
$ref=&$this->ref($key);
return array_pop($ref);
}
/**
* Add element to the beginning of hive array variable
* @return mixed
* @param $key string
* @param $val mixed
**/
function unshift($key,$val) {
$ref=&$this->ref($key);
array_unshift($ref,$val);
return $val;
}
/**
* Remove first element of hive array variable
* @return mixed
* @param $key string
**/
function shift($key) {
$ref=&$this->ref($key);
return array_shift($ref);
}
/**
* Merge array with hive array variable
* @return array
* @param $key string
* @param $src string|array
* @param $keep bool
**/
function merge($key,$src,$keep=FALSE) {
$ref=&$this->ref($key);
if (!$ref)
$ref=[];
$out=array_merge($ref,is_string($src)?$this->hive[$src]:$src);
if ($keep)
$ref=$out;
return $out;
}
/**
* Extend hive array variable with default values from $src
* @return array
* @param $key string
* @param $src string|array
* @param $keep bool
**/
function extend($key,$src,$keep=FALSE) {
$ref=&$this->ref($key);
if (!$ref)
$ref=[];
$out=array_replace_recursive(
is_string($src)?$this->hive[$src]:$src,$ref);
if ($keep)
$ref=$out;
return $out;
}
/**
* Convert backslashes to slashes
* @return string
* @param $str string
**/
function fixslashes($str) {
return $str?strtr($str,'\\','/'):$str;
}
/**
* Split comma-, semi-colon, or pipe-separated string
* @return array
* @param $str string
* @param $noempty bool
**/
function split($str,$noempty=TRUE) {
return array_map('trim',
preg_split('/[,;|]/',$str?:'',0,$noempty?PREG_SPLIT_NO_EMPTY:0));
}
/**
* Convert PHP expression/value to compressed exportable string
* @return string
* @param $arg mixed
* @param $stack array
**/
function stringify($arg,?array $stack=NULL) {
if ($stack) {
foreach ($stack as $node)
if ($arg===$node)
return '*RECURSION*';
}
else
$stack=[];
switch (gettype($arg)) {
case 'object':
$str='';
foreach (get_object_vars($arg) as $key=>$val)
$str.=($str?',':'').
$this->export($key).'=>'.
$this->stringify($val,
array_merge($stack,[$arg]));
return get_class($arg).'::__set_state(['.$str.'])';
case 'array':
$str='';
$num=isset($arg[0]) &&
ctype_digit(implode('',array_keys($arg)));
foreach ($arg as $key=>$val)
$str.=($str?',':'').
($num?'':($this->export($key).'=>')).
$this->stringify($val,array_merge($stack,[$arg]));
return '['.$str.']';
default:
return $this->export($arg);
}
}
/**
* Flatten array values and return as CSV string
* @return string
* @param $args array
**/
function csv(array $args) {
return implode(',',array_map('stripcslashes',
array_map([$this,'stringify'],$args)));
}
/**
* Convert snakecase string to camelcase
* @return string
* @param $str string
**/
function camelcase($str) {
return preg_replace_callback(
'/_(\pL)/u',
function($match) {
return strtoupper($match[1]);
},
$str
);
}
/**
* Convert camelcase string to snakecase
* @return string
* @param $str string
**/
function snakecase($str) {
return strtolower(preg_replace('/(?!^)\p{Lu}/u','_\0',$str));
}
/**
* Return -1 if specified number is negative, 0 if zero,
* or 1 if the number is positive
* @return int
* @param $num mixed
**/
function sign($num) {
return $num?($num/abs($num)):0;
}
/**
* Extract values of array whose keys start with the given prefix
* @return array
* @param $arr array
* @param $prefix string
**/
function extract($arr,$prefix) {
$out=[];
foreach (preg_grep('/^'.preg_quote($prefix,'/').'/',array_keys($arr))
as $key)
$out[substr($key,strlen($prefix))]=$arr[$key];
return $out;
}
/**
* Convert class constants to array
* @return array
* @param $class object|string
* @param $prefix string
**/
function constants($class,$prefix='') {
$ref=new ReflectionClass($class);
return $this->extract($ref->getconstants(),$prefix);
}
/**
* Generate 64bit/base36 hash
* @return string
* @param $str
**/
function hash($str) {
return str_pad(base_convert(
substr(sha1($str?:''),-16),16,36),11,'0',STR_PAD_LEFT);
}
/**
* Return Base64-encoded equivalent
* @return string
* @param $data string
* @param $mime string
**/
function base64($data,$mime) {
return 'data:'.$mime.';base64,'.base64_encode($data);
}
/**
* Convert special characters to HTML entities
* @return string
* @param $str string
**/
function encode($str) {
return @htmlspecialchars($str,$this->hive['BITMASK'],
$this->hive['ENCODING'])?:$this->scrub($str);
}
/**
* Convert HTML entities back to characters
* @return string
* @param $str string
**/
function decode($str) {
return htmlspecialchars_decode($str,$this->hive['BITMASK']);
}
/**
* Invoke callback recursively for all data types
* @return mixed
* @param $arg mixed
* @param $func callback
* @param $stack array
**/
function recursive($arg,$func,$stack=[]) {
if ($stack) {
foreach ($stack as $node)
if ($arg===$node)
return $arg;
}
switch (gettype($arg)) {
case 'object':
$ref=new ReflectionClass($arg);
if ($ref->iscloneable()) {
$arg=clone($arg);
$cast=($it=is_a($arg,'IteratorAggregate'))?
iterator_to_array($arg):get_object_vars($arg);
foreach ($cast as $key=>$val) {
// skip inaccessible properties #350
if (!$it && !isset($arg->$key))
continue;
$arg->$key=$this->recursive(
$val,$func,array_merge($stack,[$arg]));
}
}
return $arg;
case 'array':
$copy=[];
foreach ($arg as $key=>$val)
$copy[$key]=$this->recursive($val,$func,
array_merge($stack,[$arg]));
return $copy;
}
return $func($arg);
}
/**
* Remove HTML tags (except those enumerated) and non-printable
* characters to mitigate XSS/code injection attacks
* @return mixed
* @param $arg mixed
* @param $tags string
**/
function clean($arg,$tags=NULL) {
return $this->recursive($arg,
function($val) use($tags) {
if ($tags!='*')
$val=trim(strip_tags($val??'',
'<'.implode('><',$this->split($tags)).'>'));
return trim(preg_replace(
'/[\x00-\x08\x0B\x0C\x0E-\x1F]/','',$val));
}
);
}
/**
* Similar to clean(), except that variable is passed by reference
* @return mixed
* @param $var mixed
* @param $tags string
**/
function scrub(&$var,$tags=NULL) {
return $var=$this->clean($var,$tags);
}
/**
* Return locale-aware formatted string
* @return string
**/
function format() {
$args=func_get_args();
$val=array_shift($args);
// Get formatting rules
$conv=localeconv();
return preg_replace_callback(
'/\{\s*(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'.
'(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?\s*)?)*)'.
'(?:,\s*(?P<prop>.+?))?)?)?\s*\}/',
function($expr) use($args,$conv) {
/**
* @var string $pos
* @var string $mod
* @var string $type
* @var string $prop
*/
extract($expr);
/**
* @var string $thousands_sep
* @var string $negative_sign
* @var string $positive_sign
* @var string $frac_digits
* @var string $decimal_point
* @var string $int_curr_symbol
* @var string $currency_symbol
*/
extract($conv);
if (!array_key_exists($pos,$args))
return $expr[0];
if (isset($type)) {
if (isset($this->hive['FORMATS'][$type]))
return $this->call(
$this->hive['FORMATS'][$type],
[
$args[$pos],
isset($mod)?$mod:null,
isset($prop)?$prop:null
]
);
$php81=version_compare(PHP_VERSION, '8.1.0')>=0;
switch ($type) {
case 'plural':
preg_match_all('/(?<tag>\w+)'.
'(?:\s*\{\s*(?<data>.*?)\s*\})/',
$mod,$matches,PREG_SET_ORDER);
$ord=['zero','one','two'];
foreach ($matches as $match) {
/** @var string $tag */
/** @var string $data */
extract($match);
if (isset($ord[$args[$pos]]) &&
$tag==$ord[$args[$pos]] || $tag=='other')
return str_replace('#',$args[$pos],$data);
}
case 'number':
if (isset($mod))
switch ($mod) {
case 'integer':
return number_format(
$args[$pos],0,'',$thousands_sep);
case 'currency':