forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBBCodeParser.php
More file actions
3676 lines (3147 loc) · 111 KB
/
BBCodeParser.php
File metadata and controls
3676 lines (3147 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 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\Parsers;
use SMF\Attachment;
use SMF\Autolinker;
use SMF\BrowserDetector;
use SMF\Config;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\Parser;
use SMF\Sapi;
use SMF\Theme;
use SMF\Time;
use SMF\Url;
use SMF\Utils;
/**
* Parses Bulletin Board Code in a string and converts it to HTML.
*/
class BBCodeParser extends Parser
{
/*********************
* Internal properties
*********************/
/**
* @var ?string
*
* Regular expression to match all BBCode tags.
*/
protected ?string $alltags_regex = null;
/**
* @var bool
*
* Whether smileys should be parsed while we are parsing BBCode.
*/
protected bool $smileys = true;
/**
* @var array
*
* Version of self::$codes used for internal processing.
*/
private array $bbc_codes = [];
/**
* @var array
*
* Copies of $this->bbc_codes for different locales.
*/
private array $bbc_lang_locales = [];
/**
* @var string
*
* URL of this host/domain. Needed for the YouTube BBCode.
*/
private string $hosturl;
/**
* @var string
*
* The string in which to parse BBCode.
*/
private string $message = '';
/**
* @var array
*
* BBCode tags that are currently open at any given step of processing
* $this->message.
*/
private array $open_tags = [];
/**
* @var ?array
*
* The last item of $this->open_tags.
*/
private ?array $inside = null;
/**
* @var int|bool
*
* Current position in $this->message.
*/
private int|bool $pos = -1;
/**
* @var ?int
*
* Position where current BBCode tag ends.
*/
private ?int $pos1 = null;
/**
* @var int
*
* Previous value of $this->pos.
*/
private ?int $last_pos = null;
/**
* @var array
*
* Placeholders used to protect certain strings from processing.
*/
private array $placeholders = [];
/**
* @var int
*
* How many placeholders we have created.
*/
private int $placeholders_counter = 0;
/**
* @var string
*
* The sprintf format used to create placeholders.
* Uses private use Unicode characters to prevent conflicts.
*/
private string $placeholder_template = "\u{E03C}" . '%1$s' . "\u{E03E}";
/****************************
* Internal static properties
****************************/
/**
* @var array
*
* Definitions of supported BBCodes.
*
* The BBCode definitions are formatted as an array, with keys as follows:
*
* tag: The tag's name - should be lowercase!
*
* type: One of...
* - (missing): [tag]parsed content[/tag]
* - unparsed_equals: [tag=xyz]parsed content[/tag]
* - parsed_equals: [tag=parsed data]parsed content[/tag]
* - unparsed_content: [tag]unparsed content[/tag]
* - closed: [tag], [tag/], [tag /]
* - unparsed_commas: [tag=1,2,3]parsed content[/tag]
* - unparsed_commas_content: [tag=1,2,3]unparsed content[/tag]
* - unparsed_equals_content: [tag=...]unparsed content[/tag]
*
* parameters: An optional array of parameters, for the form
* [tag abc=123]content[/tag]. The array is an associative array
* where the keys are the parameter names, and the values are an
* array which may contain the following:
* - match: a regular expression to validate and match the value.
* - quoted: true if the value should be quoted.
* - validate: callback to evaluate on the data, which is $data.
* - value: a string in which to replace $1 with the data.
* Either value or validate may be used, not both.
* - optional: true if the parameter is optional.
* - default: a default value for missing optional parameters.
*
* test: A regular expression to test immediately after the tag's
* '=', ' ' or ']'. Typically, should have a \] at the end.
* Optional.
*
* content: Only available for unparsed_content, closed,
* unparsed_commas_content, and unparsed_equals_content.
* $1 is replaced with the content of the tag. Parameters
* are replaced in the form {param}. For unparsed_commas_content,
* $2, $3, ..., $n are replaced. The form {txt_*} can be used to
* insert Lang::$txt strings, e.g. {txt_code} will be replaced with
* the value of Lang::$txt['code'].
*
* before: Only when content is not used, to go before any
* content. For unparsed_equals, $1 is replaced with the value.
* For unparsed_commas, $1, $2, ..., $n are replaced.
*
* after: Similar to before in every way, except that it is used
* when the tag is closed.
*
* disabled_content: Used in place of content when the tag is
* disabled. For closed, default is '', otherwise it is '$1' if
* block_level is false, '<div>$1</div>' elsewise.
*
* disabled_before: Used in place of before when disabled. Defaults
* to '<div>' if block_level, '' if not.
*
* disabled_after: Used in place of after when disabled. Defaults
* to '</div>' if block_level, '' if not.
*
* block_level: Set to true the tag is a "block level" tag, similar
* to HTML. Block level tags cannot be nested inside tags that are
* not block level, and will not be implicitly closed as easily.
* One break following a block level tag may also be removed.
*
* trim: If set to 'inside', whitespace after the begin tag will be
* removed. If set to 'outside', whitespace after the end tag will
* meet the same fate.
*
* validate: A callback to validate the data as $data. Four arguments
* will be passed to the callback: &$tag, &$data, $disabled, $params.
* Depending on the tag's type, $data may be a string or an array of
* strings (corresponding to the replacement.)
*
* quoted: When type is 'unparsed_equals' or 'parsed_equals' only,
* may be not set, 'optional', or 'required' corresponding to if
* the content may be quoted. This allows the parser to read
* [tag="abc]def[esdf]"] properly.
*
* require_parents: An array of tag names, or not set. If set, the
* enclosing tag *must* be one of the listed tags, or parsing won't
* occur.
*
* require_children: Similar to require_parents, if set children
* won't be parsed if they are not in the list.
*
* disallow_children: Similar to, but very different from,
* require_children, if it is set the listed tags will not be
* parsed inside the tag.
*
* parsed_tags_allowed: An array restricting what BBC can be in the
* parsed_equals parameter, if desired.
*/
protected static array $codes = [
[
'tag' => 'abbr',
'type' => 'unparsed_equals',
'before' => '<abbr title="$1">',
'after' => '</abbr>',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
],
// Legacy (and just an alias for [abbr] even when enabled)
[
'tag' => 'acronym',
'type' => 'unparsed_equals',
'before' => '<abbr title="$1">',
'after' => '</abbr>',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
],
[
'tag' => 'anchor',
'type' => 'unparsed_equals',
'test' => '[#]?([A-Za-z][A-Za-z0-9_\-]*)\]',
'before' => '<span id="post_$1">',
'after' => '</span>',
],
[
'tag' => 'attach',
'type' => 'unparsed_content',
'parameters' => [
'id' => ['match' => '(\d+)'],
'alt' => ['optional' => true],
'width' => ['optional' => true, 'match' => '(\d+)'],
'height' => ['optional' => true, 'match' => '(\d+)'],
'display' => ['optional' => true, 'match' => '(link|embed)'],
],
'content' => '$1',
'validate' => __CLASS__ . '::attachValidate',
],
[
'tag' => 'b',
'before' => '<strong>',
'after' => '</strong>',
],
// Legacy (equivalent to [ltr] or [rtl])
[
'tag' => 'bdo',
'type' => 'unparsed_equals',
'before' => '<bdo dir="$1">',
'after' => '</bdo>',
'test' => '(rtl|ltr)\]',
'block_level' => true,
],
// Legacy (alias of [color=black])
[
'tag' => 'black',
'before' => '<span style="color: black;" class="bbc_color">',
'after' => '</span>',
],
// Legacy (alias of [color=blue])
[
'tag' => 'blue',
'before' => '<span style="color: blue;" class="bbc_color">',
'after' => '</span>',
],
[
'tag' => 'br',
'type' => 'closed',
// We put a class on this to force the Markdown parser to preserve it.
'content' => '<br class="bbc_br">',
],
[
'tag' => 'center',
'before' => '<div class="centertext"><div class="inline-block">',
'after' => '</div></div>',
'block_level' => true,
],
[
'tag' => 'code',
'type' => 'unparsed_content',
'content' => '<div class="codeheader"><span class="code">{txt_code}</span> <a class="codeoperation smf_select_text">{txt_code_select}</a> <a class="codeoperation smf_expand_code hidden" data-shrink-txt="{txt_code_shrink}" data-expand-txt="{txt_code_expand}">{txt_code_expand}</a></div><code class="bbc_code">$1</code>',
'validate' => __CLASS__ . '::codeValidate',
'block_level' => true,
],
[
'tag' => 'code',
'type' => 'unparsed_equals_content',
'content' => '<div class="codeheader"><span class="code">{txt_code}</span> ($2) <a class="codeoperation smf_select_text">{txt_code_select}</a> <a class="codeoperation smf_expand_code hidden" data-shrink-txt="{txt_code_shrink}" data-expand-txt="{txt_code_expand}">{txt_code_expand}</a></div><code class="bbc_code">$1</code>',
'validate' => __CLASS__ . '::codeValidate',
'block_level' => true,
],
[
'tag' => 'color',
'type' => 'unparsed_equals',
'test' => '(#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\s?,\s?){2}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\))\]',
'before' => '<span style="color: $1;" class="bbc_color">',
'after' => '</span>',
],
[
'tag' => 'email',
'type' => 'unparsed_content',
'content' => '<a href="mailto:$1" class="bbc_email">$1</a>',
'validate' => __CLASS__ . '::emailValidate',
],
[
'tag' => 'email',
'type' => 'unparsed_equals',
'before' => '<a href="mailto:$1" class="bbc_email">',
'after' => '</a>',
'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
],
// Legacy (and just a link even when not disabled)
[
'tag' => 'flash',
'type' => 'unparsed_commas_content',
'test' => '\d+,\d+\]',
'content' => '<a href="$1" target="_blank" rel="noopener">$1</a>',
'validate' => __CLASS__ . '::flashValidate',
],
[
'tag' => 'float',
'type' => 'unparsed_equals',
'test' => '(left|right)(\s+max=\d+(?:%|px|em|rem|ex|pt|pc|ch|vw|vh|vmin|vmax|cm|mm|in)?)?\]',
'before' => '<div $1>',
'after' => '</div>',
'validate' => __CLASS__ . '::floatValidate',
'trim' => 'outside',
'block_level' => true,
],
// Legacy (alias of [url] with an FTP URL)
[
'tag' => 'ftp',
'type' => 'unparsed_content',
'content' => '<a href="$1" class="bbc_link" target="_blank" rel="noopener">$1</a>',
'validate' => __CLASS__ . '::ftpValidate',
],
// Legacy (alias of [url] with an FTP URL)
[
'tag' => 'ftp',
'type' => 'unparsed_equals',
'before' => '<a href="$1" class="bbc_link" target="_blank" rel="noopener">',
'after' => '</a>',
'validate' => __CLASS__ . '::ftpValidate',
'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
],
[
'tag' => 'font',
'type' => 'unparsed_equals',
'test' => '[A-Za-z0-9_,\-\s]+?\]',
'before' => '<span style="font-family: $1;" class="bbc_font">',
'after' => '</span>',
],
// Legacy (one of those things that should not be done)
[
'tag' => 'glow',
'type' => 'unparsed_commas',
'test' => '[#0-9a-zA-Z\-]{3,12},([012]\d{1,2}|\d{1,2})(,[^]]+)?\]',
'before' => '<span style="text-shadow: $1 1px 1px 1px">',
'after' => '</span>',
],
// Legacy (alias of [color=green])
[
'tag' => 'green',
'before' => '<span style="color: green;" class="bbc_color">',
'after' => '</span>',
],
// For the h1-h6 tags, the element name will often change in the final
// output, but the class will not. For example, `<h1 class="bbc_h1">`
// might become `<h5 class="bbc_h1">` in the final output.
[
'tag' => 'h1',
'before' => '<h1 class="bbc_h1">',
'after' => '</h1>',
'block_level' => true,
],
[
'tag' => 'h2',
'before' => '<h2 class="bbc_h2">',
'after' => '</h2>',
'block_level' => true,
],
[
'tag' => 'h3',
'before' => '<h3 class="bbc_h3">',
'after' => '</h3>',
'block_level' => true,
],
[
'tag' => 'h4',
'before' => '<h4 class="bbc_h4">',
'after' => '</h4>',
'block_level' => true,
],
[
'tag' => 'h5',
'before' => '<h5 class="bbc_h5">',
'after' => '</h5>',
'block_level' => true,
],
[
'tag' => 'h6',
'before' => '<h6 class="bbc_h6">',
'after' => '</h6>',
'block_level' => true,
],
[
'tag' => 'html',
'type' => 'unparsed_content',
'content' => '<div class="bbc_html">$1</div>',
'block_level' => true,
'disabled_content' => '$1',
],
[
'tag' => 'hr',
'type' => 'closed',
'content' => '<hr>',
'block_level' => true,
],
[
'tag' => 'i',
'before' => '<em>',
'after' => '</em>',
],
[
'tag' => 'img',
'type' => 'unparsed_content',
'parameters' => [
'alt' => ['optional' => true],
'title' => ['optional' => true],
'width' => ['optional' => true, 'value' => ' width="$1"', 'match' => '(\d+)'],
'height' => ['optional' => true, 'value' => ' height="$1"', 'match' => '(\d+)'],
],
'content' => '$1',
'validate' => __CLASS__ . '::imgValidate',
'disabled_content' => '($1)',
],
[
'tag' => 'iurl',
'type' => 'unparsed_content',
'content' => '<a href="$1" class="bbc_link">$1</a>',
'validate' => __CLASS__ . '::urlValidate',
],
[
'tag' => 'iurl',
'type' => 'unparsed_equals',
'quoted' => 'optional',
'before' => '<a href="$1" class="bbc_link">',
'after' => '</a>',
'validate' => __CLASS__ . '::urlValidate',
'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
],
[
'tag' => 'justify',
'before' => '<div class="justifytext">',
'after' => '</div>',
'block_level' => true,
],
[
'tag' => 'left',
'before' => '<div class="lefttext">',
'after' => '</div>',
'block_level' => true,
],
[
'tag' => 'li',
'before' => '<li>',
'after' => '</li>',
'trim' => 'outside',
'require_parents' => ['list'],
'block_level' => true,
'disabled_before' => '',
'disabled_after' => '<br>',
],
[
'tag' => 'list',
'before' => '<ul class="bbc_list">',
'after' => '</ul>',
'trim' => 'inside',
'require_children' => ['li', 'list'],
'block_level' => true,
],
[
'tag' => 'list',
'parameters' => [
'type' => ['match' => '(none|disc|circle|square)'],
],
'before' => '<ul class="bbc_list" style="list-style-type: {type};">',
'after' => '</ul>',
'trim' => 'inside',
'require_children' => ['li'],
'block_level' => true,
],
[
'tag' => 'list',
'parameters' => [
'type' => ['match' => '(decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|upper-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha)'],
],
'before' => '<ol class="bbc_list" style="list-style-type: {type};">',
'after' => '</ol>',
'trim' => 'inside',
'require_children' => ['li'],
'block_level' => true,
],
[
'tag' => 'ltr',
'before' => '<bdo dir="ltr">',
'after' => '</bdo>',
'block_level' => true,
],
[
'tag' => 'me',
'type' => 'unparsed_equals',
'before' => '<div class="meaction">* $1 ',
'after' => '</div>',
'quoted' => 'optional',
'block_level' => true,
'disabled_before' => '/me ',
'disabled_after' => '<br>',
],
[
'tag' => 'member',
'type' => 'unparsed_equals',
'before' => '<a href="{scripturl}?action=profile;u=$1" class="mention" data-mention="$1">@',
'after' => '</a>',
],
// Legacy (horrible memories of the 1990s)
[
'tag' => 'move',
'before' => '<marquee>',
'after' => '</marquee>',
'block_level' => true,
'disallow_children' => ['move'],
],
[
'tag' => 'nobbc',
'type' => 'unparsed_content',
'content' => '$1',
],
// This one only exists to prevent autolinking in its content.
[
'tag' => 'nolink',
'before' => '',
'after' => '',
],
[
'tag' => 'php',
'type' => 'unparsed_content',
'content' => '<code class="phpcode">$1</code>',
'validate' => __CLASS__ . '::phpValidate',
'block_level' => false,
'disabled_content' => '$1',
],
[
'tag' => 'pre',
'before' => '<pre>',
'after' => '</pre>',
],
[
'tag' => 'quote',
'before' => '<blockquote><cite>{txt_quote}</cite>',
'after' => '</blockquote>',
'trim' => 'both',
'block_level' => true,
],
[
'tag' => 'quote',
'parameters' => [
'author' => ['match' => '(.{1,192}?)', 'quoted' => true],
],
'before' => '<blockquote><cite>{txt_quote_from}: {author}</cite>',
'after' => '</blockquote>',
'trim' => 'both',
'block_level' => true,
],
[
'tag' => 'quote',
'type' => 'parsed_equals',
'before' => '<blockquote><cite>{txt_quote_from}: $1</cite>',
'after' => '</blockquote>',
'trim' => 'both',
'quoted' => 'optional',
// Don't allow everything to be embedded with the author name.
'parsed_tags_allowed' => ['url', 'iurl', 'ftp'],
'block_level' => true,
],
[
'tag' => 'quote',
'parameters' => [
'author' => ['match' => '([^<>]{1,192}?)'],
'link' => ['match' => '(?:board=\d+;)?((?:topic|threadid)=[\dmsg#\./]{1,40}(?:;start=[\dmsg#\./]{1,40})?|msg=\d+?|action=profile;u=\d+)'],
'date' => ['match' => '(\d+)', 'validate' => 'SMF\\Time::stringFromUnix'],
],
'before' => '<blockquote><cite><a href="{scripturl}?{link}">{txt_quote_from}: {author} {txt_search_on} {date}</a></cite>',
'after' => '</blockquote>',
'trim' => 'both',
'block_level' => true,
],
[
'tag' => 'quote',
'parameters' => [
'author' => ['match' => '(.{1,192}?)'],
],
'before' => '<blockquote><cite>{txt_quote_from}: {author}</cite>',
'after' => '</blockquote>',
'trim' => 'both',
'block_level' => true,
],
// Legacy (alias of [color=red])
[
'tag' => 'red',
'before' => '<span style="color: red;" class="bbc_color">',
'after' => '</span>',
],
[
'tag' => 'right',
'before' => '<div class="righttext"><div class="inline-block">',
'after' => '</div></div>',
'block_level' => true,
],
[
'tag' => 'rtl',
'before' => '<bdo dir="rtl">',
'after' => '</bdo>',
'block_level' => true,
],
[
'tag' => 's',
'before' => '<s>',
'after' => '</s>',
],
// Legacy (never a good idea)
[
'tag' => 'shadow',
'type' => 'unparsed_commas',
'test' => '[#0-9a-zA-Z\-]{3,12},(left|right|top|bottom|[0123]\d{0,2})\]',
'before' => '<span style="text-shadow: $1 $2">',
'after' => '</span>',
'validate' => __CLASS__ . '::shadowValidate',
],
[
'tag' => 'size',
'type' => 'unparsed_equals',
'test' => '([1-9][\d]?p[xt]|small(?:er)?|large[r]?|x[x]?-(?:small|large)|medium|(0\.[1-9]|[1-9](\.[\d][\d]?)?)?em)\]',
'before' => '<span style="font-size: $1;" class="bbc_size">',
'after' => '</span>',
],
[
'tag' => 'size',
'type' => 'unparsed_equals',
'test' => '[1-7]\]',
'before' => '<span style="font-size: $1;" class="bbc_size">',
'after' => '</span>',
'validate' => __CLASS__ . '::sizeValidate',
],
[
'tag' => 'sub',
'before' => '<sub>',
'after' => '</sub>',
],
[
'tag' => 'sup',
'before' => '<sup>',
'after' => '</sup>',
],
[
'tag' => 'table',
'before' => '<table class="bbc_table">',
'after' => '</table>',
'trim' => 'inside',
'require_children' => ['tr'],
'block_level' => true,
],
[
'tag' => 'td',
'before' => '<td>',
'after' => '</td>',
'require_parents' => ['tr'],
'trim' => 'outside',
'block_level' => true,
'disabled_before' => '',
'disabled_after' => '',
],
[
'tag' => 'time',
'type' => 'unparsed_content',
'content' => '$1',
'validate' => __CLASS__ . '::timeValidate',
],
[
'tag' => 'tr',
'before' => '<tr>',
'after' => '</tr>',
'require_parents' => ['table'],
'require_children' => ['td'],
'trim' => 'both',
'block_level' => true,
'disabled_before' => '',
'disabled_after' => '',
],
[
'tag' => 'tt',
'before' => '<code class="bbc_tt">',
'after' => '</code>',
],
[
'tag' => 'u',
'before' => '<u>',
'after' => '</u>',
],
[
'tag' => 'url',
'type' => 'unparsed_content',
'content' => '<a href="$1" class="bbc_link" target="_blank" rel="noopener">$1</a>',
'validate' => __CLASS__ . '::urlValidate',
],
[
'tag' => 'url',
'type' => 'unparsed_equals',
'quoted' => 'optional',
'before' => '<a href="$1" class="bbc_link" target="_blank" rel="noopener">',
'after' => '</a>',
'validate' => __CLASS__ . '::urlValidate',
'disallow_children' => ['email', 'ftp', 'url', 'iurl'],
'disabled_after' => ' ($1)',
],
// Legacy (alias of [color=white])
[
'tag' => 'white',
'before' => '<span style="color: white;" class="bbc_color">',
'after' => '</span>',
],
[
'tag' => 'youtube',
'type' => 'unparsed_content',
'content' => '<div class="videocontainer"><div><iframe frameborder="0" src="https://www.youtube.com/embed/$1?origin={hosturl}&wmode=opaque" data-youtube-id="$1" allowfullscreen loading="lazy"></iframe></div></div>',
'disabled_content' => '<a href="https://www.youtube.com/watch?v=$1" target="_blank" rel="noopener">https://www.youtube.com/watch?v=$1</a>',
'block_level' => true,
],
];
/**
* @var array
*
* Itemcodes are an alternative syntax for creating lists.
*/
protected static array $itemcodes = [
'*' => 'disc',
'@' => 'disc',
'+' => 'square',
'x' => 'square',
'#' => 'square',
'o' => 'circle',
'O' => 'circle',
'0' => 'circle',
];
/**
* @var bool
*
* Tracks whether the integration_bbc_codes hook was called.
*/
private static bool $integrate_bbc_codes_done = false;
/**
* @var array
*
* Reusable instances of this class.
*/
private static array $parsers = [];
/*****************
* Public methods.
*****************/
/**
* Constructor.
*/
public function __construct(bool $for_print = false)
{
$this->for_print = $for_print;
parent::__construct();
self::integrateBBC();
usort(
self::$codes,
fn ($a, $b) => $a['tag'] <=> $b['tag'],
);
}
/**
* Parse bulletin board code in a string.
*
* @param string|bool $message The string to parse.
* @param bool $smileys Whether to parse smileys. Default: true.
* @param string|int $cache_id The cache ID.
* If $cache_id is left empty, an ID will be generated automatically.
* Manually specifying a ID is helpful in cases when an integration hook
* wants to identify particular strings to act upon, but is otherwise
* unnecessary.
* @param array $parse_tags If set, only parses these tags rather than all of them.
* @return string The parsed string.
*/
public function parse(string $message, bool $smileys = true, string|int $cache_id = '', array $parse_tags = []): string
{
// Don't waste cycles
if (strval($message) === '') {
return '';
}
// Ensure we start with a clean slate.
$this->resetRuntimeProperties();
$this->message = $message;
$this->smileys = $smileys;
$this->parse_tags = $parse_tags;
$this->setDisabled();
$this->setBbcCodes();
// Clean up any cut/paste issues we may have
$this->message = self::sanitizeMSCutPaste($this->message);
// If the load average is too high, don't parse the BBC.
if ($this->highLoadAverage()) {
return $this->message;
}
if (!self::$enable_bbc) {
if ($this->smileys === true) {
$this->message = SmileyParser::load()->parse($this->message);
}
$this->message = $this->fixHtml($this->message);
return $this->message;
}
// Do the job.
$this->parseMessage();
return $this->message;
}
/**
* Converts HTML to BBC.
*
* Only used by ManageBoards.php (and possibly mods).
*
* @param string $string Text containing HTML.
* @return string The string with HTML converted to BBC.
*/
public function unparse(string $string): string
{
// Replace newlines with spaces, as that's how browsers usually interpret them.
$string = preg_replace('~\s*[\r\n]+\s*~', ' ', $string);
// Though some of us love paragraphs, the parser will do better with breaks.
$string = preg_replace('~</p>\s*?<p~i', '</p><br><p', $string);
$string = preg_replace('~</p>\s*(?!<)~i', '</p><br>', $string);
// Safari/webkit wraps lines in Wysiwyg in <div>'s.
if (BrowserDetector::isBrowser('webkit')) {
$string = preg_replace(['~<div(?:\s(?:[^<>]*?))?' . '>~i', '</div>'], ['<br>', ''], $string);
}
// If there's a trailing break get rid of it - Firefox tends to add one.
$string = preg_replace('~<br\s?/?' . '>$~i', '', $string);
// Remove any formatting within code tags.
if (str_contains($string, '[code')) {
$string = preg_replace('~<br\s?/?' . '>~i', '#smf_br_spec_grudge_cool!#', $string);
$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
// Only mess with stuff outside [code] tags.
for ($i = 0, $n = count($parts); $i < $n; $i++) {
// Value of 2 means we're inside the tag.
if ($i % 4 == 2) {
$parts[$i] = strip_tags($parts[$i]);
}
}
$string = strtr(implode('', $parts), ['#smf_br_spec_grudge_cool!#' => '<br>']);
}
// Remove scripts, style and comment blocks.
$string = preg_replace('~<script[^>]*[^/]?' . '>.*?</script>~i', '', $string);
$string = preg_replace('~<style[^>]*[^/]?' . '>.*?</style>~i', '', $string);
$string = preg_replace('~\\<\\!--.*?-->~i', '', $string);
$string = preg_replace('~\\<\\!\\[CDATA\\[.*?\\]\\]\\>~i', '', $string);
// Only try to buy more time if the client didn't quit.
if (connection_aborted()) {
Sapi::resetTimeout();
}
$parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|</[A-Za-z]+>)~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$replacement = '';
$stack = [];
foreach ($parts as $part) {
// Opening tag.
if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1) {
// If it's being closed instantly, we can't deal with it...yet.
if ($matches[5] === '/') {
continue;
}
// Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
$styles = explode(';', strtr((string) $matches[3], ['"' => '']));
$curElement = $matches[2];
$precedingStyle = $matches[1];
$afterStyle = $matches[4];
$curCloseTags = '';
$extra_attr = '';
foreach ($styles as $type_value_pair) {
// Remove spaces and convert uppercase letters.
$clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
// Something like 'font-weight: bold' is expected here.
if (!str_contains($clean_type_value_pair, ':')) {
continue;
}
// Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
list($style_type, $style_value) = explode(':', $type_value_pair);
$style_value = trim($style_value);
switch (trim($style_type)) {
case 'font-weight':
if ($style_value === 'bold') {
$curCloseTags .= '[/b]';
$replacement .= '[b]';
}
break;
case 'text-decoration':
if ($style_value == 'underline') {
$curCloseTags .= '[/u]';
$replacement .= '[u]';
} elseif ($style_value == 'line-through') {
$curCloseTags .= '[/s]';
$replacement .= '[s]';
}
break;
case 'text-align':
if ($style_value == 'left') {
$curCloseTags .= '[/left]';
$replacement .= '[left]';
} elseif ($style_value == 'center') {
$curCloseTags .= '[/center]';
$replacement .= '[center]';
} elseif ($style_value == 'right') {
$curCloseTags .= '[/right]';
$replacement .= '[right]';
}
break;