-
Notifications
You must be signed in to change notification settings - Fork 254
/
Copy pathUtils.php
2615 lines (2263 loc) · 86.8 KB
/
Utils.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
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2024 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 3.0 Alpha 2
*/
declare(strict_types=1);
namespace SMF;
use SMF\Db\DatabaseApi as Db;
/**
* Holds some widely used stuff, like $context and $smcFunc.
*/
class Utils
{
use BackwardCompatibility;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
private static $backcompat = [
'prop_names' => [
'context' => 'context',
'smcFunc' => 'smcFunc',
],
];
/*****************
* Class constants
*****************/
/**
* Regular expression to match all named HTML entities and numeric entities.
*/
public const ENT_LIST = '&(?' . '>A(?' . '>acute|breve|grave|tilde|Elig|lpha' .
'|macr|ring|scr|uml|fr|nd|c(?' . '>irc|y)|o(?' . '>gon|pf))|B(?' . '>rev' .
'e|arv|opf|scr|cy|fr|e(?' . '>cause|ta))|C(?' . '>ircle(?' . '>Times|Plu' .
's|Dot)|ross|Hcy|dot|scr|fr|hi|up(?' . '>Cap|)|a(?' . '>cute|p(?' . '>it' .
'alDifferentialD|))|c(?' . '>onint|aron|edil|irc)|e(?' . '>nterDot|dilla' .
')|o(?' . '>product|lon(?' . '>e|)|n(?' . '>tourIntegral|gruent)))|D(?' .
'>Dotrahd|elta|Jcy|Scy|Zcy|fr|a(?' . '>gger|shv|rr)|c(?' . '>aron|y)|i(?' .
'>fferentialD|acritical(?' . '>DoubleAcute|Acute|Tilde))|o(?' . '>tDot|u' .
'ble(?' . '>ContourIntegral|RightTee|UpArrow|Dot|L(?' . '>ongRightArrow|' .
'eftArrow))|pf|wn(?' . '>Arrow(?' . '>UpArrow|Bar)|Breve|Right(?' . '>Te' .
'eVector|VectorBar)|arrow|Left(?' . '>RightVector|TeeVector|VectorBar)|T' .
'ee(?' . '>Arrow|)))|s(?' . '>trok|cr))|E(?' . '>psilon|acute|grave|xist' .
's|qual|dot|sim|uml|NG|TH|fr|ta|c(?' . '>aron|irc|y)|m(?' . '>acr|pty(?' .
'>VerySmallSquare|SmallSquare))|o(?' . '>gon|pf))|F(?' . '>illedSmallSqu' .
'are|cy|fr|o(?' . '>uriertrf|pf))|G(?' . '>reater(?' . '>Greater|Tilde)|' .
'breve|amma(?' . '>d|)|Jcy|dot|opf|scr|fr|c(?' . '>edil|irc|y)|g)|H(?' .
'>ilbertSpace|umpEqual|ARDcy|strok|circ|fr|a(?' . '>cek|t)|o(?' . '>rizo' .
'ntalLine|pf))|I(?' . '>acute|grave|tilde|Jlig|Ecy|Ocy|dot|fr|c(?' . '>i' .
'rc|y)|m(?' . '>plies|a(?' . '>ginaryI|cr))|n(?' . '>visibleTimes|t(?' .
'>egral|))|o(?' . '>gon|pf|ta)|u(?' . '>kcy|ml))|J(?' . '>ukcy|opf|fr|c(' .
'?' . '>irc|y)|s(?' . '>ercy|cr))|K(?' . '>appa|Hcy|Jcy|opf|scr|fr|c(?' .
'>edil|y))|L(?' . '>midot|Jcy|fr|a(?' . '>cute|mbda|ng|rr)|c(?' . '>aron' .
'|edil|y)|e(?' . '>ft(?' . '>RightVector|VectorBar|ArrowBar|Floor|Do(?' .
'>ubleBracket|wn(?' . '>TeeVector|VectorBar))|Up(?' . '>DownVector|TeeVe' .
'ctor|VectorBar)|T(?' . '>riangle(?' . '>Equal|Bar)|ee(?' . '>Vector|Arr' .
'ow)))|ss(?' . '>Tilde|Less))|l|o(?' . '>werRightArrow|ng(?' . '>LeftRig' .
'htArrow|RightArrow)|pf)|s(?' . '>trok|h))|M(?' . '>inusPlus|opf|ap|cy|f' .
'r|e(?' . '>diumSpace|llintrf)|u)|N(?' . '>ewLine|acute|tilde|Jcy|scr|fr' .
'|c(?' . '>aron|edil|y)|o(?' . '>Break|t(?' . '>RightTriangle(?' . '>Equ' .
'al|Bar)|Precedes(?' . '>SlantEqual|Equal)|Greater(?' . '>FullEqual|Grea' .
'ter|Less)|Nested(?' . '>GreaterGreater|LessLess)|Equal|Tilde|Le(?' . '>' .
'ftTriangleBar|ss(?' . '>Equal|))|C(?' . '>ongruent|upCap)|S(?' . '>quar' .
'eSu(?' . '>perset(?' . '>Equal|)|bset(?' . '>Equal|))|u(?' . '>persetEq' .
'ual|bsetEqual|cceeds(?' . '>SlantEqual|Equal|Tilde|)))|))|u)|O(?' . '>p' .
'enCurly(?' . '>DoubleQuote|Quote)|acute|dblac|grave|Elig|opf|uml|ver(?' .
'>Parenthesis|Brac(?' . '>ket|e))|fr|ti(?' . '>lde|mes)|c(?' . '>irc|y)|' .
'm(?' . '>icron|acr|ega)|r|s(?' . '>lash|cr))|P(?' . '>cy|fr|hi|i|r(?' .
'>ecedesSlantEqual|ime|)|s(?' . '>cr|i))|Q(?' . '>scr|fr)|R(?' . '>uleDe' .
'layed|everse(?' . '>UpEquilibrium|Element)|ight(?' . '>VectorBar|Ceilin' .
'g|Floor|Do(?' . '>ubleBracket|wn(?' . '>TeeVector|Vector(?' . '>Bar|)))' .
'|Up(?' . '>DownVector|TeeVector|Vector(?' . '>Bar|))|A(?' . '>ngleBrack' .
'et|rrowBar)|T(?' . '>eeVector|riangle(?' . '>Equal|Bar)))|fr|ho|a(?' .
'>cute|rrtl|ng)|c(?' . '>aron|edil|y)|o(?' . '>undImplies|pf))|S(?' . '>' .
'OFTcy|acute|igma|opf|scr|tar|fr|H(?' . '>CHcy|cy)|c(?' . '>aron|edil|ir' .
'c|y|)|q(?' . '>uare(?' . '>Su(?' . '>persetEqual|bsetEqual)|)|rt)|u(?' .
'>cceeds(?' . '>Equal|Tilde)|pset|b(?' . '>setEqual|)))|T(?' . '>ildeFul' .
'lEqual|ripleDot|HORN|opf|fr|S(?' . '>Hcy|cy)|a(?' . '>b|u)|c(?' . '>aro' .
'n|edil|y)|h(?' . '>eta|i(?' . '>ckSpace|nSpace))|s(?' . '>trok|cr))|U(?' .
'>dblac|grave|tilde|macr|ring|scr|uml|br(?' . '>eve|cy)|fr|a(?' . '>cute' .
'|rr(?' . '>ocir|))|c(?' . '>irc|y)|n(?' . '>ionPlus|der(?' . '>Parenthe' .
'sis|Brace))|o(?' . '>gon|pf)|p(?' . '>perRightArrow|DownArrow|downarrow' .
'|ArrowBar|TeeArrow|silon))|V(?' . '>vdash|Dash|dash(?' . '>l|)|bar|opf|' .
'scr|cy|er(?' . '>ticalSeparator|bar)|fr)|W(?' . '>circ|opf|scr|fr)|X(?' .
'>opf|scr|fr|i)|Y(?' . '>acute|Acy|Icy|Ucy|opf|scr|uml|fr|c(?' . '>irc|y' .
'))|Z(?' . '>acute|Hcy|dot|opf|scr|fr|c(?' . '>aron|y)|e(?' . '>roWidthS' .
'pace|ta))|a(?' . '>acute|breve|grave|tilde|elig|ring|uml|c(?' . '>irc|E' .
'|d|y|)|f(?' . '>r|)|l(?' . '>eph|pha)|m(?' . '>a(?' . '>cr|lg)|p)|n(?' .
'>d(?' . '>slope|and|d|v|)|g(?' . '>zarr|msd(?' . '>a(?' . '>a|b|c|d|e|f' .
'|g|h)|)|sph|le|rt(?' . '>vb(?' . '>d|)|)|e))|o(?' . '>gon|pf)|p(?' . '>' .
'acir|prox|id|os|E|e)|s(?' . '>cr|t)|w(?' . '>conint|int))|b(?' . '>karo' .
'w|rvbar|dquo|Not|brk(?' . '>tbrk|)|fr|ig(?' . '>triangle(?' . '>down|up' .
')|sqcup|uplus|c(?' . '>irc|ap|up)|o(?' . '>times|plus))|a(?' . '>ck(?' .
'>epsilon|prime|simeq)|r(?' . '>vee|wed))|c(?' . '>ong|y)|e(?' . '>mptyv' .
'|t(?' . '>ween|a|h))|l(?' . '>ock|a(?' . '>cktriangle(?' . '>right|down' .
'|left|)|nk)|k(?' . '>34|1(?' . '>2|4)))|n(?' . '>ot|e(?' . '>quiv|))|o(' .
'?' . '>wtie|pf|x(?' . '>minus|plus|box|D(?' . '>L|R|l|r)|H(?' . '>D|U|d' .
'|u|)|U(?' . '>L|R|l|r)|V(?' . '>H|L|R|h|l|r|)|d(?' . '>L|R|l|r)|h(?' .
'>D|U|d|u)|u(?' . '>L|R|l|r)|v(?' . '>H|L|R|h|l|r|)))|s(?' . '>emi|cr|im' .
'|ol(?' . '>hsub|b|))|u(?' . '>ll|mp(?' . '>E|)))|c(?' . '>ylcty|lubs|td' .
'ot|dot|fr|ir(?' . '>fnint|scir|mid|E|c(?' . '>eq|)|)|a(?' . '>cute|ret|' .
'p(?' . '>brcup|and|dot|c(?' . '>ap|up)|s|))|c(?' . '>edil|irc|ups(?' .
'>sm|)|a(?' . '>ron|ps))|e(?' . '>mptyv|nt)|h(?' . '>eck|cy|i)|o(?' . '>' .
'ngdot|lon(?' . '>eq|)|m(?' . '>ma(?' . '>t|)|p(?' . '>lexes|fn|))|p(?' .
'>f|y(?' . '>sr|)))|r(?' . '>arr|oss)|s(?' . '>cr|u(?' . '>b(?' . '>e|)|' .
'p(?' . '>e|)))|u(?' . '>larrp|darr(?' . '>l|r)|esc|p(?' . '>brcap|dot|o' .
'r|c(?' . '>ap|up)|s|)|r(?' . '>vearrowleft|arr(?' . '>m|)|ren|ly(?' .
'>eqprec|wedge|vee)))|w(?' . '>conint|int))|d(?' . '>bkarow|dotseq|wangl' .
'e|lcrop|harl|tdot|Har|jcy|a(?' . '>gger|leth|shv|rr)|c(?' . '>aron|y)|e' .
'(?' . '>mptyv|lta|g)|f(?' . '>isht|r)|i(?' . '>amond(?' . '>suit|)|sin|' .
'v(?' . '>ide|onx))|o(?' . '>ublebarwedge|wndownarrows|llar|pf|t(?' . '>' .
'eqdot|))|r(?' . '>bkarow|c(?' . '>orn|rop))|s(?' . '>trok|ol|c(?' . '>r' .
'|y))|z(?' . '>igrarr|cy))|e(?' . '>rarr|dot|fr|a(?' . '>cute|ster)|c(?' .
'>aron|ir(?' . '>c|)|y)|g(?' . '>rave|s(?' . '>dot|)|)|l(?' . '>inters|l' .
'|s(?' . '>dot|)|)|m(?' . '>acr|pty|sp(?' . '>1(?' . '>3|4)|))|n(?' . '>' .
'sp|g)|o(?' . '>gon|pf)|p(?' . '>lus|ar(?' . '>sl|)|si)|q(?' . '>vparsl|' .
'colon|u(?' . '>ivDD|als|est))|s(?' . '>dot|cr|im)|t(?' . '>a|h)|u(?' .
'>ml|ro)|x(?' . '>cl|p(?' . '>onentiale|ectation)))|f(?' . '>allingdotse' .
'q|partint|emale|ilig|jlig|nof|scr|cy|f(?' . '>ilig|l(?' . '>lig|ig)|r)|' .
'l(?' . '>lig|tns|at)|o(?' . '>pf|r(?' . '>all|kv))|r(?' . '>own|a(?' .
'>sl|c(?' . '>45|78|1(?' . '>3|4|5|6|8)|2(?' . '>3|5)|3(?' . '>4|5|8)|5(' .
'?' . '>6|8)))))|g(?' . '>vertneqq|breve|imel|rave|dot|jcy|opf|El|fr|a(?' .
'>cute|mma(?' . '>d|)|p)|c(?' . '>irc|y)|e(?' . '>qq|s(?' . '>dot(?' .
'>o(?' . '>l|)|)|cc|l(?' . '>es|)|)|)|g|l(?' . '>E|a|j|)|n(?' . '>sim|ap' .
'|e(?' . '>qq|))|s(?' . '>cr|im(?' . '>e|l))|t(?' . '>quest|lPar|c(?' .
'>ir|c)|r(?' . '>eqless|arr|dot)|))|h(?' . '>circ|Arr|fr|a(?' . '>irsp|l' .
'f|r(?' . '>dcy|r(?' . '>cir|w|)))|e(?' . '>arts|llip|rcon)|o(?' . '>mth' .
't|rbar|arr|pf)|s(?' . '>trok|cr)|y(?' . '>bull|phen))|i(?' . '>acute|gr' .
'ave|quest|tilde|jlig|prod|fr|c(?' . '>irc|y|)|e(?' . '>xcl|cy)|i(?' .
'>iint|nfin|ota)|m(?' . '>ped|of|a(?' . '>gline|cr))|n(?' . '>care|odot|' .
'fin(?' . '>tie|)|t(?' . '>larhk|cal))|o(?' . '>gon|cy|pf|ta)|s(?' . '>c' .
'r|in(?' . '>dot|E|s(?' . '>v|)|v))|u(?' . '>kcy|ml))|j(?' . '>math|ukcy' .
'|opf|fr|c(?' . '>irc|y)|s(?' . '>ercy|cr))|k(?' . '>green|appa|hcy|jcy|' .
'opf|scr|fr|c(?' . '>edil|y))|l(?' . '>vertneqq|Barr|Har|jcy|par(?' . '>' .
'lt|)|gE|ur(?' . '>dshar|uhar)|A(?' . '>tail|arr)|E|a(?' . '>emptyv|cute' .
'|gran|mbda|quo|ng(?' . '>le|d)|rr(?' . '>bfs|sim|fs|hk|lp|pl|tl|)|p|t(?' .
'>ail|e(?' . '>s|)|))|b(?' . '>arr|brk|r(?' . '>ac(?' . '>e|k)|k(?' . '>' .
'sl(?' . '>d|u)|e)))|c(?' . '>aron|e(?' . '>dil|il)|y)|d(?' . '>ca|sh|r(' .
'?' . '>ushar|dhar))|e(?' . '>ft(?' . '>rightharpoons|harpoon(?' . '>dow' .
'n|up))|q|s(?' . '>dot(?' . '>o(?' . '>r|)|)|cc|g(?' . '>es|)|s(?' . '>d' .
'ot|gtr|eq(?' . '>qgtr|gtr))|))|f(?' . '>isht|r)|h(?' . '>arul|blk)|l(?' .
'>corner|hard|arr|tri|)|m(?' . '>idot|oust)|n(?' . '>sim|ap|e(?' . '>qq|' .
'))|o(?' . '>oparrowright|ngleftarrow|times|a(?' . '>ng|rr)|p(?' . '>lus' .
'|ar|f)|w(?' . '>ast|bar)|z(?' . '>enge|f))|r(?' . '>hard|arr|tri|m)|s(?' .
'>aquo|trok|cr|im(?' . '>e|g))|t(?' . '>quest|hree|imes|larr|c(?' . '>ir' .
'|c)|r(?' . '>Par|i)|))|m(?' . '>DDot|dash|lcp|scr|fr|ho|a(?' . '>rker|c' .
'r|l(?' . '>tese|e)|p)|c(?' . '>omma|y)|i(?' . '>cro|nus(?' . '>d(?' .
'>u|)|)|d(?' . '>cir|))|o(?' . '>dels|pf)|u(?' . '>map|))|n(?' . '>dash|' .
'jcy|fr|is(?' . '>d|)|G(?' . '>g|t)|L(?' . '>eftarrow|l|t(?' . '>v|))|V(' .
'?' . '>Dash|dash)|a(?' . '>cute|bla|tur(?' . '>als|)|ng|p(?' . '>prox|i' .
'd|os|E))|b(?' . '>ump(?' . '>e|)|sp)|c(?' . '>edil|ong(?' . '>dot|)|up|' .
'a(?' . '>ron|p)|y)|e(?' . '>arhk|xist|Arr|dot|sim)|g(?' . '>sim|tr|e(?' .
'>q|s))|h(?' . '>Arr|par)|l(?' . '>sim|tri(?' . '>e|)|dr|E|e(?' . '>ft(?' .
'>rightarrow|arrow)|s))|o(?' . '>pf|t(?' . '>niv(?' . '>a|b|c)|in(?' .
'>dot|E|v(?' . '>b|c)|)|))|p(?' . '>olint|ar(?' . '>allel|sl|t)|r)|r(?' .
'>Arr|arr(?' . '>c|w|))|s(?' . '>hortmid|ime|cr|u(?' . '>b(?' . '>E|)|p(' .
'?' . '>set(?' . '>eqq|)|)))|t(?' . '>riangleright|ilde|lg)|u(?' . '>m(?' .
'>ero|sp|)|)|v(?' . '>infin|Dash|Harr|dash|sim|ap|g(?' . '>e|t)|l(?' .
'>Arr|e|t(?' . '>rie|))|r(?' . '>trie|Arr))|w(?' . '>near|Arr|ar(?' . '>' .
'row|hk)))|o(?' . '>elig|hbar|vbar|opf|uml|ti(?' . '>mesas|lde)|S|a(?' .
'>cute|st)|c(?' . '>ir(?' . '>c|)|y)|d(?' . '>blac|sold|ash|iv)|f(?' .
'>cir|r)|g(?' . '>rave|on|t)|l(?' . '>arr|ine|c(?' . '>ross|ir)|t)|m(?' .
'>acr|ega|i(?' . '>cron|nus|d))|p(?' . '>erp|ar)|r(?' . '>slope|igof|arr' .
'|or|d(?' . '>erof|f|m|)|v|)|s(?' . '>lash|ol))|p(?' . '>uncsp|ar(?' .
'>a|s(?' . '>im|l)|t)|cy|er(?' . '>tenk|cnt|iod|mil|p)|fr|h(?' . '>one|i' .
')|i(?' . '>tchfork|v|)|l(?' . '>anck(?' . '>h|)|us(?' . '>acir|cir|sim|' .
'two|mn|d(?' . '>o|u)|e|))|o(?' . '>intint|und|pf)|r(?' . '>urel|ime(?' .
'>s|)|ec(?' . '>approx|sim|eq|n(?' . '>approx|eqq|sim)|)|E|o(?' . '>d|f(' .
'?' . '>alar|line|surf)|p))|s(?' . '>cr|i))|q(?' . '>prime|opf|scr|fr|u(' .
'?' . '>atint|est|ot))|r(?' . '>uluhar|moust|nmid|rarr|Har|lm|A(?' . '>t' .
'ail|arr)|a(?' . '>emptyv|quo|ng(?' . '>d|e)|rr(?' . '>bfs|sim|ap|fs|hk|' .
'pl|tl|c|w)|c(?' . '>ute|e)|t(?' . '>ail|io(?' . '>nals|)))|b(?' . '>brk' .
'|rk(?' . '>sl(?' . '>d|u)|e))|c(?' . '>aron|edil|ub|y)|d(?' . '>ldhar|q' .
'uo|ca|sh)|e(?' . '>aline|ct|g)|f(?' . '>isht|r)|h(?' . '>ar(?' . '>d|u(' .
'?' . '>l|))|o(?' . '>v|))|i(?' . '>singdotseq|ghtleft(?' . '>harpoons|a' .
'rrows)|ng)|o(?' . '>times|a(?' . '>ng|rr)|p(?' . '>lus|ar|f))|p(?' . '>' .
'polint|ar(?' . '>gt|))|s(?' . '>aquo|cr|h|q(?' . '>uo|b))|t(?' . '>hree' .
'|imes|ri(?' . '>ltri|))|x)|s(?' . '>padesuit|acute|bquo|rarr|zlig|dot(?' .
'>b|e|)|fr|c(?' . '>polint|aron|edil|irc|E|n(?' . '>sim|E)|y)|e(?' . '>a' .
'rhk|swar|Arr|ct|mi|xt)|h(?' . '>ortparallel|arp|c(?' . '>hcy|y)|y)|i(?' .
'>gma(?' . '>v|)|m(?' . '>plus|rarr|dot|eq|ne|g(?' . '>E|)|l(?' . '>E|)|' .
'))|m(?' . '>eparsl|ashp|ile|t(?' . '>e(?' . '>s|)|))|o(?' . '>ftcy|pf|l' .
'(?' . '>b(?' . '>ar|)|))|q(?' . '>uarf|su(?' . '>pset|b)|c(?' . '>ap(?' .
'>s|)|up(?' . '>s|)))|s(?' . '>etmn|cr)|t(?' . '>raight(?' . '>epsilon|p' .
'hi)|ar(?' . '>f|))|u(?' . '>cc(?' . '>curlyeq|napprox|approx|)|ng|b(?' .
'>edot|mult|plus|rarr|dot|E|s(?' . '>etneq(?' . '>q|)|im|u(?' . '>b|p))|' .
')|m|p(?' . '>larr|mult|plus|hs(?' . '>ol|ub)|nE|1|2|3|d(?' . '>sub|ot)|' .
'e(?' . '>dot|)|s(?' . '>et(?' . '>eqq|neq)|im|u(?' . '>b|p))|))|w(?' .
'>nwar|Arr|ar(?' . '>hk|r)))|t(?' . '>woheadrightarrow|elrec|prime|fr|a(' .
'?' . '>rget|u)|c(?' . '>aron|edil|y)|h(?' . '>orn|e(?' . '>re4|ta(?' .
'>sym|)))|i(?' . '>mes(?' . '>b(?' . '>ar|)|d|)|nt)|o(?' . '>ea|p(?' .
'>bot|cir|f(?' . '>ork|)))|r(?' . '>pezium|ade|i(?' . '>angle(?' . '>dow' .
'n|q|)|minus|plus|time|dot|sb))|s(?' . '>trok|hcy|c(?' . '>r|y)))|u(?' .
'>wangle|grave|macr|Har|scr|uml|br(?' . '>eve|cy)|a(?' . '>cute|rr)|c(?' .
'>irc|y)|d(?' . '>blac|arr|har)|f(?' . '>isht|r)|h(?' . '>arl|blk)|l(?' .
'>tri|c(?' . '>orner|rop))|o(?' . '>gon|pf)|p(?' . '>uparrows|si(?' . '>' .
'h|))|r(?' . '>ing|tri|c(?' . '>orner|rop))|t(?' . '>ilde|dot))|v(?' .
'>zigzag|dash|nsub|rtri|Bar(?' . '>v|)|opf|cy|fr|a(?' . '>ngrt|r(?' . '>' .
'triangleleft|supsetneqq|kappa))|e(?' . '>llip|rt|e(?' . '>bar|eq))|s(?' .
'>cr|u(?' . '>pne|bn(?' . '>E|e))))|w(?' . '>circ|opf|scr|ed(?' . '>bar|' .
'geq)|fr|p|r)|x(?' . '>wedge|hArr|lArr|map|nis|scr|vee|fr|i|o(?' . '>dot' .
'|pf))|y(?' . '>icy|opf|scr|ac(?' . '>ute|y)|en|fr|c(?' . '>irc|y)|u(?' .
'>cy|ml))|z(?' . '>igrarr|acute|dot|eta|hcy|opf|scr|fr|c(?' . '>aron|y)|' .
'w(?' . '>nj|j))|#(?' . '>\d+|x[0-9a-fA-F]+));';
/**
* Regular expression to match all forms of the non-breaking space entity.
*/
public const ENT_NBSP = '&(?' . '>nbsp|#(?' . '>x0*A0|0*160));';
/**
* @var string
*
* Used to force the browser not to collapse tabs.
*
* This will normally be replaced in the final output with a real tab
* character wrapped in a span with "white-space: pre" applied to it.
* But if this substitute string somehow makes it into the final output,
* it will still look like an appropriately sized string of white space.
*/
public const TAB_SUBSTITUTE = "\u{200B}\u{2007}\u{2007}\u{2007}\u{2007}\u{200B}";
/**************************
* Public static properties
**************************/
/**
* @var array
*
* SMF's venerable $context variable, now available as Utils::$context.
*/
public static $context = [
// Assume UTF-8 until proven otherwise.
'utf8' => true,
'character_set' => 'UTF-8',
// Define a list of icons used across multiple places.
'stable_icons' => [
'xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp',
'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'poll', 'moved',
'recycled', 'clip',
],
// Define an array for custom profile fields placements.
'cust_profile_fields_placement' => [
'standard',
'icons',
'above_signature',
'below_signature',
'below_avatar',
'above_member',
'bottom_poster',
'before_member',
'after_member',
],
// Define an array for content-related <meta> elements (e.g. description,
// keywords, Open Graph) for the HTML head.
'meta_tags' => [],
// Define an array of allowed HTML tags.
'allowed_html_tags' => [
'<img>',
'<div>',
],
// Define a list of allowed tags for descriptions.
'description_allowed_tags' => [
'abbr', 'anchor', 'b', 'br', 'center', 'color', 'font', 'hr', 'i',
'img', 'iurl', 'left', 'li', 'list', 'ltr', 'pre', 'right', 's',
'sub', 'sup', 'table', 'td', 'tr', 'u', 'url',
],
// Define a list of deprecated BBC tags.
// Even when enabled, they'll only work in old posts and not new ones.
'legacy_bbc' => [
'acronym', 'bdo', 'black', 'blue', 'flash', 'ftp', 'glow',
'green', 'move', 'red', 'shadow', 'white',
],
// Define a list of BBC tags that require permissions to use.
'restricted_bbc' => [
'html',
],
// Login Cookie times. Format: time => txt
'login_cookie_times' => [
3153600 => 'always_logged_in',
60 => 'one_hour',
1440 => 'one_day',
10080 => 'one_week',
43200 => 'one_month',
],
'show_spellchecking' => false,
];
/**
* @var array
*
* Backward compatibility aliases of various utility functions.
*/
public static $smcFunc = [
'entity_decode' => __CLASS__ . '::entityDecode',
'sanitize_entities' => __CLASS__ . '::sanitizeEntities',
'entity_fix' => __CLASS__ . '::entityFix',
'htmlspecialchars' => __CLASS__ . '::htmlspecialchars',
'htmltrim' => __CLASS__ . '::htmlTrim',
'strlen' => __CLASS__ . '::entityStrlen',
'strpos' => __CLASS__ . '::entityStrpos',
'substr' => __CLASS__ . '::entitySubstr',
'strtolower' => __CLASS__ . '::strtolower',
'strtoupper' => __CLASS__ . '::strtoupper',
'ucfirst' => __CLASS__ . '::ucfirst',
'ucwords' => __CLASS__ . '::ucwords',
'convert_case' => __CLASS__ . '::convertCase',
'normalize' => __CLASS__ . '::normalize',
'truncate' => __CLASS__ . '::truncate',
'json_encode' => __CLASS__ . '::jsonEncode',
'json_decode' => 'smf_json_decode',
'random_int' => __CLASS__ . '::randomInt',
'random_bytes' => __CLASS__ . '::randomBytes',
];
/***********************
* Public static methods
***********************/
/**
* (Re)initializes some $context values that need to be set dynamically.
*/
public static function load(): void
{
// Used to force browsers to download fresh CSS and JavaScript when necessary
if (isset(Config::$modSettings['browser_cache'])) {
self::$context['browser_cache'] = '?' . preg_replace('~\W~', '', strtolower(SMF_FULL_VERSION)) . '_' . Config::$modSettings['browser_cache'];
}
// UTF-8?
if (isset(Config::$modSettings['global_character_set'])) {
self::$context['character_set'] = Config::$modSettings['global_character_set'];
self::$context['utf8'] = self::$context['character_set'] === 'UTF-8';
}
// Load up our $context['server'] data for backwards compatibility
Sapi::load();
}
/**
* Decodes and sanitizes HTML entities.
*
* If database does not support 4-byte UTF-8 characters, entities for 4-byte
* characters are left in place, unless the $mb4 argument is set to true.
*
* @param string $string The string in which to decode entities.
* @param bool $mb4 If true, always decode 4-byte UTF-8 characters.
* Default: false.
* @param int $flags Flags to pass to html_entity_decode.
* Default: ENT_QUOTES | ENT_HTML5.
* @param bool $nbsp_to_space If true, decode ' ' to space character.
* Default: false.
* @return string The string with the entities decoded.
*/
public static function entityDecode(string $string, bool $mb4 = false, int $flags = ENT_QUOTES | ENT_HTML5, bool $nbsp_to_space = false): string
{
// Don't waste time on empty strings.
if (trim($string) === '') {
return $string;
}
// In theory this is always UTF-8, but...
if (empty(self::$context['character_set'])) {
$charset = is_callable('mb_detect_encoding') ? mb_detect_encoding($string) : 'UTF-8';
} elseif (str_contains(self::$context['character_set'], 'ISO-8859-') && !in_array(self::$context['character_set'], ['ISO-8859-5', 'ISO-8859-15'])) {
$charset = 'ISO-8859-1';
} else {
$charset = self::$context['character_set'];
}
// Enables consistency with the behaviour of un_htmlspecialchars.
if ($nbsp_to_space) {
$string = preg_replace('~' . self::ENT_NBSP . '~u', ' ', $string);
}
// Do the deed.
$string = html_entity_decode($string, $flags, $charset);
// Remove any illegal character entities.
$string = self::sanitizeEntities($string);
// Finally, make sure we don't break the database.
if (!$mb4) {
$string = self::fixUtf8mb4($string);
}
return $string;
}
/**
* Fixes double-encoded entities in a string.
*
* @param string $string The string.
* @return string The fixed string.
*/
public static function entityFix(string $string): string
{
return preg_replace('~&(' . substr(self::ENT_LIST, 1, -1) . ');~', '&$1;', $string);
}
/**
* Replaces HTML entities for invalid characters with a substitute.
*
* The default substitute is the entity for the replacement character U+FFFD
* (a.k.a. the question-mark-in-a-box).
*
* !!! Warning !!! Setting $substitute to '' in order to delete invalid
* entities from the string can create unexpected security problems. See
* https://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters for an
* explanation.
*
* @param string $string The string to sanitize.
* @param string $substitute Replacement for the invalid entities.
* Default: '�'
* @return string The sanitized string.
*/
public static function sanitizeEntities(string $string, string $substitute = '�'): string
{
if (!str_contains($string, '&#')) {
return $string;
}
// Disallow entities for control characters, non-characters, etc.
return preg_replace_callback(
'~(&#(0*\d{1,7}|x0*[0-9a-fA-F]{1,6});)~',
function ($matches) use ($substitute) {
$num = $matches[2][0] === 'x' ? hexdec(substr($matches[2], 1)) : (int) $matches[2];
if (
// Control characters (except \t, \n, and \r).
($num < 0x20 && $num !== 0x9 && $num !== 0xA && $num !== 0xD)
|| ($num >= 0x7F && $num < 0xA0)
// UTF-16 surrogate pairs.
|| ($num >= 0xD800 && $num <= 0xDFFF)
// Code points that are guaranteed never to be characters.
|| ($num >= 0xFDD0 && $num <= 0xFDEF)
|| (in_array($num % 0x10000, [0xFFFE, 0xFFFF]))
// Out of range.
|| $num > 0x10FFFF
) {
return $substitute;
}
return '&#' . $num . ';';
},
(string) $string,
);
}
/**
* Replaces invalid characters with a substitute.
*
* !!! Warning !!! Setting $substitute to '' in order to delete invalid
* characters from the string can create unexpected security problems. See
* https://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters for an
* explanation.
*
* @param string $string The string to sanitize.
* @param int $level Controls filtering of invisible formatting characters.
* 0: Allow valid formatting characters. Use for sanitizing text in posts.
* 1: Allow necessary formatting characters. Use for sanitizing usernames.
* 2: Disallow all formatting characters. Use for internal comparisons
* only, such as in the word censor, search contexts, etc.
* Default: 0.
* @param string|null $substitute Replacement string for the invalid characters.
* If not set, the Unicode replacement character (U+FFFD) will be used
* (or a fallback like "?" if necessary).
* @return string|false The sanitized string, or false on failure.
*/
public static function sanitizeChars(string $string, int $level = 0, ?string $substitute = null): string|false
{
$string = (string) $string;
$level = min(max((int) $level, 0), 2);
// What substitute character should we use?
if (isset($substitute)) {
$substitute = strval($substitute);
} elseif (!empty(Utils::$context['utf8'])) {
// Raw UTF-8 bytes for U+FFFD.
$substitute = "\xEF\xBF\xBD";
} elseif (!empty(Utils::$context['character_set']) && is_callable('mb_decode_numericentity')) {
// Get whatever the default replacement character is for this encoding.
$substitute = mb_decode_numericentity('�', [0xFFFD, 0xFFFD, 0, 0xFFFF], Utils::$context['character_set']);
} else {
$substitute = '?';
}
// Fix any invalid byte sequences.
if (!empty(Utils::$context['character_set'])) {
// For UTF-8, this preg_match test is much faster than mb_check_encoding.
$malformed = !empty(Utils::$context['utf8']) ? @preg_match('//u', $string) === false && preg_last_error() === PREG_BAD_UTF8_ERROR : (!is_callable('mb_check_encoding') || !mb_check_encoding($string, Utils::$context['character_set']));
if ($malformed) {
// mb_convert_encoding will replace invalid byte sequences with our substitute.
if (is_callable('mb_convert_encoding')) {
if (!is_callable('mb_ord')) {
require_once Config::$sourcedir . '/Subs-Compat.php';
}
$substitute_ord = $substitute === '' ? 'none' : mb_ord($substitute, Utils::$context['character_set']);
$mb_substitute_character = mb_substitute_character();
mb_substitute_character($substitute_ord);
$string = mb_convert_encoding($string, Utils::$context['character_set'], Utils::$context['character_set']);
mb_substitute_character($mb_substitute_character);
} else {
return false;
}
}
}
// Fix any weird vertical space characters.
$string = Utils::normalizeSpaces($string, true);
// Deal with unwanted control characters, invisible formatting characters, and other creepy-crawlies.
if (!empty(Utils::$context['utf8'])) {
$string = (string) Unicode\Utf8String::create($string)->sanitizeInvisibles($level, $substitute);
} else {
$string = preg_replace('/[^\P{Cc}\t\r\n]/', $substitute, $string);
}
return $string;
}
/**
* Normalizes space characters and line breaks.
*
* @param string $string The string to sanitize.
* @param bool $vspace If true, replaces all line breaks and vertical space
* characters with "\n". Default: true.
* @param bool $hspace If true, replaces horizontal space characters with a
* plain " " character. (Note: tabs are not replaced unless the
* 'replace_tabs' option is supplied.) Default: false.
* @param array $options An array of boolean options. Possible values are:
* - no_breaks: Vertical spaces are replaced by " " instead of "\n".
* - replace_tabs: If true, tabs are replaced by " " chars.
* - collapse_hspace: If true, removes extra horizontal spaces.
* @return string|false The sanitized string, or false on failure.
*/
public static function normalizeSpaces(string $string, bool $vspace = true, bool $hspace = false, array $options = []): string|false
{
$string = (string) $string;
$vspace = !empty($vspace);
$hspace = !empty($hspace);
if (!$vspace && !$hspace) {
return $string;
}
$options['no_breaks'] = !empty($options['no_breaks']);
$options['collapse_hspace'] = !empty($options['collapse_hspace']);
$options['replace_tabs'] = !empty($options['replace_tabs']);
$patterns = [];
$replacements = [];
if ($vspace) {
// \R is like \v, except it handles "\r\n" as a single unit.
$patterns[] = '/\R/' . (Utils::$context['utf8'] ? 'u' : '');
$replacements[] = $options['no_breaks'] ? ' ' : "\n";
}
if ($hspace) {
// Interesting fact: Unicode properties like \p{Zs} work even when not in UTF-8 mode.
$patterns[] = '/' . ($options['replace_tabs'] ? '\h' : '\p{Zs}') . ($options['collapse_hspace'] ? '+' : '') . '/' . (Utils::$context['utf8'] ? 'u' : '');
$replacements[] = ' ';
}
return preg_replace($patterns, $replacements, $string);
}
/**
* Wrapper for standard htmlspecialchars() that ensures the output respects
* the database's support (or lack thereof) for four-byte UTF-8 characters.
*
* @param string $string The string being converted.
* @param int $flags Bitmask of flags to pass to standard htmlspecialchars().
* Default is ENT_COMPAT.
* @param string $encoding Character encoding. Default is UTF-8.
* @return string The converted string.
*/
public static function htmlspecialchars(string $string, int $flags = ENT_COMPAT, string $encoding = 'UTF-8'): string
{
$string = self::normalize($string);
return self::fixUtf8mb4(self::sanitizeEntities(\htmlspecialchars($string, $flags, $encoding)));
}
/**
* Recursively applies self::htmlspecialchars() to all elements of an array.
*
* Only affects values.
*
* @param mixed $var The string or array of strings to add entities to
* @param int $flags Bitmask of flags to pass to standard htmlspecialchars().
* Default is ENT_COMPAT.
* @param string $encoding Character encoding. Default is UTF-8.
* @return array|string The string or array of strings with entities added
*/
public static function htmlspecialcharsRecursive(mixed $var, int $flags = ENT_COMPAT, string $encoding = 'UTF-8'): array|string
{
static $level = 0;
if (!is_array($var)) {
return self::htmlspecialchars((string) $var, $flags, $encoding);
}
// Add the htmlspecialchars to every element.
foreach ($var as $k => $v) {
if ($level > 25) {
$var[$k] = null;
} else {
$level++;
$var[$k] = self::htmlspecialcharsRecursive($v, $flags, $encoding);
$level--;
}
}
return $var;
}
/**
* Replaces special entities in strings with the real characters.
*
* Functionally equivalent to htmlspecialchars_decode(), except that this also
* replaces ' ' with a simple space character.
*
* @param string $string A string.
* @param int $flags Bitmask of flags to pass to standard htmlspecialchars().
* Default is ENT_QUOTES.
* @param string $encoding Character encoding. Default is UTF-8.
* @return string|false The string without entities, or false on failure.
*/
public static function htmlspecialcharsDecode(string $string, int $flags = ENT_QUOTES, string $encoding = 'UTF-8'): string|false
{
return preg_replace('/' . self::ENT_NBSP . '/u', ' ', htmlspecialchars_decode($string, $flags));
}
/**
* Like standard ltrim(), except that it also trims entities, control
* characters, and Unicode whitespace characters beyond the ASCII range.
*
* @param string $string The string.
* @return string|false The trimmed string, or false on failure.
*/
public static function htmlTrimLeft(string $string): string|false
{
return preg_replace('~^(?' . '>[\p{Z}\p{C}]|' . self::ENT_NBSP . ')+~u', '', self::sanitizeEntities($string));
}
/**
* Like standard rtrim(), except that it also trims entities, control
* characters, and Unicode whitespace characters beyond the ASCII range.
*
* @param string $string The string.
* @return string|false The trimmed string, or false on failure.
*/
public static function htmlTrimRight(string $string): string|false
{
return preg_replace('~(?' . '>[\p{Z}\p{C}]|' . self::ENT_NBSP . ')+$~u', '', self::sanitizeEntities($string));
}
/**
* Like standard trim(), except that it also trims entities, control
* characters, and Unicode whitespace characters beyond the ASCII range.
*
* @param string $string The string.
* @return string|false The trimmed string, or false on failure.
*/
public static function htmlTrim(string $string): string|false
{
return preg_replace('~^(?' . '>[\p{Z}\p{C}]|' . self::ENT_NBSP . ')+|(?' . '>[\p{Z}\p{C}]|' . self::ENT_NBSP . ')+$~u', '', self::sanitizeEntities($string));
}
/**
* Recursively applies self::htmlTrim to all elements of an array.
*
* Only affects values.
*
* @param array|string $var The string or array of strings to trim.
* @return array|string|false The trimmed string or array of trimmed strings.
*/
public static function htmlTrimRecursive(array|string $var): array|string|false
{
static $level = 0;
// Remove spaces (32), tabs (9), returns (13, 10, and 11), nulls (0), and hard spaces. (160)
if (!is_array($var)) {
return self::htmlTrim($var);
}
// Go through all the elements and remove the whitespace.
foreach ($var as $k => $v) {
if ($level > 25) {
$var[$k] = null;
} else {
$level++;
$var[$k] = self::htmlTrimRecursive($v);
$level--;
}
}
return $var;
}
/**
* Like standard mb_strlen(), except that it counts HTML entities as
* single characters. This essentially amounts to getting the length of
* the string as it would appear to a human reader.
*
* @param string $string The string.
* @return int The length of the string.
*/
public static function entityStrlen(string $string): int
{
return strlen((string) preg_replace('~' . self::ENT_LIST . '|\X~u', '_', self::sanitizeEntities($string)));
}
/**
* Like standard mb_strpos(), except that it counts HTML entities as
* single characters.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for.
* @param int $offset Search offset within $haystack.
* @return int|false Position of $needle in $haystack, or false on failure.
*/
public static function entityStrpos(string $haystack, string $needle, int $offset = 0): int|false
{
$haystack_arr = (array) preg_split('~(' . self::ENT_LIST . '|\X)~u', self::sanitizeEntities($haystack), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if (strlen($needle) === 1) {
$result = array_search($needle, array_slice($haystack_arr, $offset));
return is_int($result) ? $result + $offset : false;
}
$needle_arr = (array) preg_split('~(' . self::ENT_LIST . '|\X)~u', self::sanitizeEntities($needle), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$needle_size = count($needle_arr);
$result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
while ((int) $result === $result) {
$offset += $result;
if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr) {
return $offset;
}
$result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
}
return false;
}
/**
* Like standard mb_substr(), except that it counts HTML entities as
* single characters.
*
* @param string $string The input string.
* @param int $offset Offset where substring will start.
* @param int $length Maximum length, in characters, of the substring.
* @return string The substring.
*/
public static function entitySubstr(string $string, int $offset, ?int $length = null): string
{
$ent_arr = (array) preg_split('~(' . self::ENT_LIST . '|\X)~u', self::sanitizeEntities($string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
return $length === null ? implode('', array_slice($ent_arr, $offset)) : implode('', array_slice($ent_arr, $offset, $length));
}
/**
* Like standard mb_str_split(), except that it counts HTML entities as
* single characters.
*
* @param string $string The input string.
* @param int $length Maximum character length of the substrings to return.
* @return array The extracted substrings.
*/
public static function entityStrSplit(string $string, int $length = 1): array
{
if ($length < 1) {
throw new \ValueError();
}
$ent_arr = (array) preg_split('~(' . Utils::ENT_LIST . '|\X)~u', Utils::sanitizeEntities($string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if ($length > 1) {
$temp = [];
while (!empty($ent_arr)) {
$temp[] = implode('', array_splice($ent_arr, 0, $length));
}
$ent_arr = $temp;
}
return $ent_arr;
}
/**
* Truncates a string to fit within the specified byte length, while making
* sure not to cut in the middle of an HTML entity or multi-byte character.
*
* The difference between this and the entitySubstr method is that this
* truncates the string to fit into a certain byte length, whereas
* entitySubstr truncates to fit into a certain visual character length.
* This difference is important when dealing with Unicode.
*
* @param string $string The input string.
* @param int $length The maximum length, in bytes, of the returned string.
* @return string|false The truncated string, or false on error.
*/
public static function truncate(string $string, int $length): string|false
{
$string = self::sanitizeEntities($string);
while (is_string($string) && strlen($string) > $length) {
$string = preg_replace('~(?:' . self::ENT_LIST . '|\X)$~u', '', $string);
}
return $string;
}
/**
* Like Utils::entitySubstr(), except that this also appends an ellipsis
* to the returned string to indicate that it was truncated (unless it
* wasn't truncated because it was already short enough).
*
* @param string $subject The string.
* @param int $len How many characters to limit it to.
* @return string The shortened string.
*/
public static function shorten(string $subject, int $len): string
{
// It was already short enough!
if (self::entityStrlen($subject) <= $len) {
return $subject;
}
// Truncate it and append an ellipsis.
return self::entitySubstr($subject, 0, $len) . '...';
}
/**
* Performs Unicode normalization on a UTF-8 string.
*
* Note that setting $form to 'kc_casefold' will cause the string's case to
* be folded and will also remove all "default ignorable code points" from
* the string. It should be used (1) when validating identifier strings that
* must be unambiguously unique, such as domain names, file names, or even
* SMF user names, or (2) when performing caseless matching of strings, such
* as when performing a search or checking for censored words in a post.
*
* @param string $string The input string.
* @param string $form A Unicode normalization form: 'c', 'd', 'kc', 'kd',
* or 'kc_casefold'.
* @return string The normalized string.
*/
public static function normalize(string $string, string $form = 'c'): string
{
return (string) Unicode\Utf8String::create($string)->normalize($form);
}
/**
* Performs case conversion on UTF-8 strings.
*
* Similar to, but with more capabilities than, mb_convert_case().
*
* Note that setting $form to 'kc_casefold' will override any value of $case
* and will always fold the case of the string. Also note that setting $form
* to 'kc_casefold' is not the same as setting $case to 'fold' and $form to
* 'kc'; specifically, setting $case to 'fold' and $form to 'kc' does not
* remove "default ignorable code points" from the string, whereas setting
* $form to 'kc_casefold' does. See notes on the normalize() method for more
* information about when 'kc_casefold' should be used.
*
* @param string $string The input string.
* @param string $case One of 'upper', 'lower', 'fold', 'title', 'ucfirst',
* or 'ucwords'.
* @param bool $simple If true, use simple maps instead of full maps.
* Default: false.
* @param string $form A Unicode normalization form: 'c', 'd', 'kc', 'kd',
* or 'kc_casefold'.
* @return string The normalized string.
*/
public static function convertCase(string $string, string $case, bool $simple = false, string $form = 'c'): string
{
// Convert numeric entities to characters, except special ones.
if (str_contains($string, '&#')) {
$string = strtr(self::sanitizeEntities($string), [
'"' => '"',
'&' => '&',
''' => ''',
'<' => '<',
'>' => '>',
' ' => ' ',
]);
$string = mb_decode_numericentity($string, [0, 0x10FFFF, 0, 0xFFFFFF], 'UTF-8');
}
// Use optimized function for compatibility casefolding.
if ($form === 'kc_casefold') {
$string = (string) Unicode\Utf8String::create($string)->normalize('kc_casefold');
}
// Everything else.
else {
$string = (string) Unicode\Utf8String::create($string)->convertCase($case, $simple)->normalize($form);
}
return self::fixUtf8mb4($string);
}
/**
* Convenience alias of Utils::convertCase($string, 'upper')
*
* @param string $string The input string.
* @return string The uppercase version of the input string.
*/
public static function strtoupper(string $string): string
{
return self::convertCase($string, 'upper');
}
/**
* Convenience alias of Utils::convertCase($string, 'lower')
*
* @param string $string The input string.
* @return string The lowercase version of the input string.
*/
public static function strtolower(string $string): string
{
return self::convertCase($string, 'lower');
}
/**
* Convenience alias of Utils::convertCase($string, 'fold')
*
* @param string $string The input string.
* @return string The casefolded version of the input string.
*/
public static function casefold(string $string): string
{
return self::convertCase($string, 'fold');
}
/**
* Convenience alias of Utils::convertCase($string, 'title')
*
* @param string $string The input string.
* @return string The titlecase version of the input string.
*/
public static function strtotitle(string $string): string
{
return self::convertCase($string, 'upper');
}
/**
* Convenience alias of Utils::convertCase($string, 'ucfirst')
*
* @param string $string The input string.
* @return string The string, but with the first character in titlecase.
*/
public static function ucfirst(string $string): string
{
return self::convertCase($string, 'ucfirst');
}
/**
* Convenience alias of Utils::convertCase($string, 'ucwords')
*
* @param string $string The input string.
* @return string The string, but with the first character of each word in titlecase.
*/
public static function ucwords(string $string): string
{
return self::convertCase($string, 'ucwords');
}