forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutolinker.php
1314 lines (1114 loc) · 38.1 KB
/
Autolinker.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;
/**
* Detects URLs in strings.
*/
class Autolinker
{
/**************************
* Public static properties
**************************/
/**
* @var string
*
* Characters to exclude from a detected URL if they appear at the end.
*/
public static string $excluded_trailing_chars = '!;:.,?';
/**
* @var array
*
* Brackets and quotation marks are problematic at the end of an IRI.
* E.g.: `http://foo.com/baz(qux)` vs. `(http://foo.com/baz_qux)`
* In the first case, the user probably intended the `)` as part of the
* IRI, but not in the second case. To account for this, we test for
* balanced pairs within the IRI.
* */
public static array $balanced_pairs = [
// Brackets and parentheses
'(' => ')', // '(' => ')',
'[' => ']', // '[' => ']',
'{' => '}', // '{' => '}',
// Double quotation marks
'"' => '"', // '"' => '"',
'“' => '”', // '“' => '”',
'„' => '”', // '„' => '”',
'‟' => '”', // '‟' => '”',
'«' => '»', // '«' => '»',
// Single quotation marks
"'" => "'", // ''' => ''',
'‘' => '’', // '‘' => '’',
'‚' => '’', // '‚' => '’',
'‛' => '’', // '‛' => '’',
'‹' => '›', // '‹' => '›',
];
/**
* @var string
*
* Regular expression character class to match all characters allowed to
* appear in a domain name.
*/
public static string $domain_label_chars = '0-9A-Za-z\-' . '\x{A0}-\x{D7FF}' .
'\x{F900}-\x{FDCF}' . '\x{FDF0}-\x{FFEF}' . '\x{10000}-\x{1FFFD}' .
'\x{20000}-\x{2FFFD}' . '\x{30000}-\x{3FFFD}' . '\x{40000}-\x{4FFFD}' .
'\x{50000}-\x{5FFFD}' . '\x{60000}-\x{6FFFD}' . '\x{70000}-\x{7FFFD}' .
'\x{80000}-\x{8FFFD}' . '\x{90000}-\x{9FFFD}' . '\x{A0000}-\x{AFFFD}' .
'\x{B0000}-\x{BFFFD}' . '\x{C0000}-\x{CFFFD}' . '\x{D0000}-\x{DFFFD}' .
'\x{E1000}-\x{EFFFD}';
/**
* @var array
*
* URI schemes that require some sort of special handling.
*
* Mods can add to this list using the integrate_autolinker_schemes hook.
*/
public static array $schemes = [
// Schemes whose URI definitions require a domain name in the
// authority (or whatever the next part of the URI is).
'need_domain' => [
'aaa', 'aaas', 'acap', 'acct', 'afp', 'cap', 'cid', 'coap',
'coap+tcp', 'coap+ws', 'coaps', 'coaps+tcp', 'coaps+ws', 'crid',
'cvs', 'dict', 'dns', 'feed', 'fish', 'ftp', 'git', 'go', 'gopher',
'h323', 'http', 'https', 'iax', 'icap', 'im', 'imap', 'ipp', 'ipps',
'irc', 'irc6', 'ircs', 'ldap', 'ldaps', 'mailto', 'mid', 'mupdate',
'nfs', 'nntp', 'pop', 'pres', 'reload', 'rsync', 'rtsp', 'sftp',
'sieve', 'sip', 'sips', 'smb', 'snmp', 'soap.beep', 'soap.beeps',
'ssh', 'svn', 'stun', 'stuns', 'telnet', 'tftp', 'tip', 'tn3270',
'turn', 'turns', 'tv', 'udp', 'vemmi', 'vnc', 'webcal', 'ws', 'wss',
'xmlrpc.beep', 'xmlrpc.beeps', 'xmpp', 'z39.50', 'z39.50r',
'z39.50s',
],
// Schemes that allow an empty authority ("://" followed by "/")
'empty_authority' => [
'file', 'ni', 'nih',
],
// Schemes that do not use an authority but still have a reasonable
// chance of working as clickable links.
'no_authority' => [
'about', 'callto', 'geo', 'gg', 'leaptofrogans', 'magnet', 'mailto',
'maps', 'news', 'ni', 'nih', 'service', 'skype', 'sms', 'tel', 'tv',
],
// Schemes that should never be autolinked.
'forbidden' => [
'javascript', 'data',
],
];
/**
* @var array
*
* BBCodes whose content should be skipped when autolinking URLs.
*
* Mods can add to this list using the integrate_bbc_codes hook.
*/
public static array $no_autolink_tags = [
'url',
'iurl',
'email',
'img',
'html',
'attach',
'ftp',
'flash',
'member',
'code',
'php',
'nobbc',
'nolink',
];
/**
* @var array
*
* BBCodes in which to fix URL strings.
*
* Mods can add to this list using the integrate_autolinker_fix_tags hook.
*/
public static array $tags_to_fix = [
'url',
'iurl',
'img',
'ftp',
];
/*********************
* Internal properties
*********************/
/**
* @var string
*
* The character encoding being used.
*/
protected string $encoding = 'UTF-8';
/**
* @var bool
*
* If true, will only link URLs with basic TLDs.
*/
protected bool $only_basic = false;
/**
* @var string
*
* PCRE regular expression to match top level domains.
*/
protected string $tld_regex;
/**
* @var string
*
* PCRE regular expression to match URLs.
*/
protected string $url_regex;
/**
* @var string
*
* PCRE regular expression to match e-mail addresses.
*/
protected string $email_regex;
/**
* @var string
*
* JavaScript regular expression to match top level domains.
*/
protected string $js_tld_regex;
/**
* @var array
*
* JavaScript regular expressions to match URLs.
*
* Due to limitations of JavaScript's regex engine, this has to be a series
* of different regexes rather than one regex like the PCRE version.
*/
protected array $js_url_regexes;
/**
* @var string
*
* JavaScript regular expression to match e-mail addresses.
*/
protected string $js_email_regex;
/**
* @var string
*
* Regular expression to match the named entities in HTML5.
*/
protected string $entities_regex;
/****************************
* Internal static properties
****************************/
/**
* @var bool
*
* Ensures we only call integrate_autolinker_schemes once.
*/
protected static bool $integrate_autolinker_schemes_done = false;
/**
* @var bool
*
* Ensures we only call integrate_autolinker_fix_tags once.
*/
protected static bool $integrate_autolinker_fix_tags_done = false;
/**
* @var self
*
* A reference to an existing, reusable instance of this class.
*/
private static self $instance;
/*****************
* Public methods.
*****************/
/**
* Constructor.
*
* @param bool $only_basic If true, will only link URLs with basic TLDs.
*/
public function __construct(bool $only_basic = false)
{
$this->only_basic = $only_basic;
if (!empty(Utils::$context['utf8'])) {
$this->encoding = 'UTF-8';
} else {
$this->encoding = !empty(Config::$modSettings['global_character_set']) ? Config::$modSettings['global_character_set'] : (!empty(Lang::$txt['lang_character_set']) ? Lang::$txt['lang_character_set'] : $this->encoding);
if (in_array($this->encoding, mb_encoding_aliases('UTF-8'))) {
$this->encoding = 'UTF-8';
}
}
if ($this->encoding !== 'UTF-8') {
self::$domain_label_chars = '0-9A-Za-z\-';
}
// In case a mod wants to control behaviour for a special URI scheme.
if (!self::$integrate_autolinker_schemes_done) {
IntegrationHook::call('integrate_autolinker_schemes', [&self::$schemes]);
self::$integrate_autolinker_schemes_done = true;
}
// For historical reasons, integrate_bbc_hook is used to give mods access to $no_autolink_tags.
BBCodeParser::integrateBBC();
}
/**
* Gets a PCRE regular expression to match all known TLDs.
*
* @return string Regular expression to match all known TLDs.
*/
public function getTldRegex(): string
{
if (!isset($this->tld_regex)) {
$this->setTldRegex();
}
return $this->tld_regex;
}
/**
* Gets a PCRE regular expression to match URLs.
*
* @return string Regular expression to match URLs.
*/
public function getUrlRegex(): string
{
if (!isset($this->url_regex)) {
$this->setUrlRegex();
}
return $this->url_regex;
}
/**
* Gets a PCRE regular expression to match email addresses.
*
* @return string Regular expression to match email addresses.
*/
public function getEmailRegex(): string
{
if (!isset($this->email_regex)) {
$this->setEmailRegex();
}
return $this->email_regex;
}
/**
* Gets a JavaScript regular expression to match all known TLDs.
*
* @return string Regular expression to match all known TLDs.
*/
public function getJavaScriptTldRegex(): string
{
if (!isset($this->js_tld_regex)) {
$this->setJavaScriptTldRegex();
}
return $this->js_tld_regex;
}
/**
* Gets a series of JavaScript regular expressions to match URLs.
*
* @return array Regular expressions to match URLs.
*/
public function getJavaScriptUrlRegexes(): array
{
if (!isset($this->js_url_regexes)) {
$this->setJavaScriptUrlRegexes();
}
return $this->js_url_regexes;
}
/**
* Gets a JavaScript regular expression to match email addresses.
*
* @return string Regular expression to match email addresses.
*/
public function getJavaScriptEmailRegex(): string
{
if (!isset($this->js_email_regex)) {
$this->setJavaScriptEmailRegex();
}
return $this->js_email_regex;
}
/**
* Detects URLs in a string.
*
* Returns an array in which the keys are the start positions of any
* detected URLs in the string, and the values are the URLs themselves.
*
* @param string $string The string to examine.
* @param bool bool $plaintext_only If true, only look for plain text URLs.
* @return array Positional info about any detected URLs.
*/
public function detectUrls(string $string, bool $plaintext_only = false): array
{
static $no_autolink_regex;
// An entity right after the URL can break the autolinker.
$this->setEntitiesRegex();
$string = preg_replace('~(' . $this->entities_regex . ')*(?=\s|$)~u', ' ', $string);
$this->setUrlRegex();
if ($plaintext_only) {
$no_autolink_regex = $no_autolink_regex ?? Utils::buildRegex(self::$no_autolink_tags);
// Overwrite the contents of all BBC markup elements that should not be autolinked.
$string = preg_replace_callback(
'~' .
// 1 = Opening BBC markup element.
'(\[' .
// 2 = BBC tag.
'(' . $no_autolink_regex . ')' .
// BBC parameters, if any.
'\b[^\]]*' .
'\])' .
// 3 = Recursive construct.
'((?' . '>' . '[^\[]|\[/?(?!' . $no_autolink_regex . ')' . '|(?1))*)' .
// 4 = Closing BBC markup element.
'(\[/\2\])' .
'~i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
fn ($matches) => $matches[1] . str_repeat('x', strlen($matches[3])) . $matches[4],
$string,
);
// Overwrite all BBC markup elements.
$string = preg_replace_callback(
'/\[[^\]]*\]/i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
fn ($matches) => str_repeat(' ', strlen($matches[0])),
$string,
);
// Overwrite the contents of all HTML anchor elements.
$string = preg_replace_callback(
'~' .
// 1 = Opening 'a' markup element.
'(<a\b[^\>]*>)' .
// 2 = Recursive construct.
'((?' . '>' . '[^<]|</?(?!a)' . '|(?1))*)' .
// 3 = Closing 'a' markup element.
'(</a>)' .
'~i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
fn ($matches) => $matches[1] . str_repeat('x', strlen($matches[2])) . $matches[3],
$string,
);
// Overwrite all HTML elements.
$string = preg_replace_callback(
'~</?(\w+)\b([^>]*)>~i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
fn ($matches) => str_repeat(' ', strlen($matches[0])),
$string,
);
}
preg_match_all(
'~' . $this->url_regex . '~i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
$string,
$matches,
PREG_OFFSET_CAPTURE,
);
$detected = [];
if (!empty($matches[0])) {
foreach ($matches[0] as $key => $match) {
$detected[$match[1]] = $match[0];
}
}
return $detected;
}
/**
* Detects email addresses in a string.
*
* Returns an array in which the keys are the start positions of any
* detected email addresses in the string, and the values are the email
* addresses themselves.
*
* @param string $string The string to examine.
* @param bool bool $plaintext_only If true, only look for plain text email
* addresses.
* @return array Positional info about any detected email addresses.
*/
public function detectEmails(string $string, bool $plaintext_only = false): array
{
// An entity right after the email address can break the autolinker.
$this->setEntitiesRegex();
$string = preg_replace('~(' . $this->entities_regex . ')*(?=\s|$)~u', ' ', $string);
$this->setEmailRegex();
preg_match_all(
'~' . ($plaintext_only ? '(?:^|\s|<br>)\K' : '') . $this->email_regex . '~i' . ($this->encoding === 'UTF-8' ? 'u' : ''),
$string,
$matches,
PREG_OFFSET_CAPTURE,
);
$detected = [];
foreach ($matches[0] as $match) {
$detected[$match[1]] = $match[0];
}
return $detected;
}
/**
* Detects plain text URLs and email addresses and formats them as BBCode
* links.
*
* @param string $string The string to autolink.
* @param bool $link_emails Whether to autolink email addresses.
* Default: true.
* @param bool $link_urls Whether to autolink URLs.
* Default: true.
* @return string The string with linked URLs.
*/
public function makeLinks(string $string, bool $link_emails = true, bool $link_urls = true): string
{
$placeholders = [];
foreach (self::$no_autolink_tags as $tag) {
$parts = preg_split('~(\[/' . $tag . '\]|\[' . $tag . '\b(?:[^\]]*)\])~i', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($parts); $i < $n; $i++) {
if ($i % 4 == 2) {
$placeholder = md5($parts[$i]);
$placeholders[$placeholder] = $parts[$i];
$parts[$i] = $placeholder;
}
}
$string = implode('', $parts);
}
if ($link_urls) {
$detected_urls = $this->detectUrls($string, true);
if (empty($detected_urls)) {
$new_string = $string;
} else {
$new_string = '';
$prev_pos = 0;
$prev_len = 0;
foreach ($detected_urls as $pos => $url) {
$new_string .= substr($string, $prev_pos + $prev_len, $pos - ($prev_pos + $prev_len));
$prev_pos = $pos;
$prev_len = strlen($url);
// If this isn't a clean URL, leave it alone.
if ($url !== (string) Url::create($url)->sanitize()) {
$new_string .= $url;
continue;
}
// Ensure the host name is in its canonical form.
$url = new Url($url, true);
if (!isset($url->scheme)) {
$url->scheme = '';
}
if ($url->scheme == 'mailto') {
if (!$link_emails) {
$new_string .= $url;
continue;
}
// Is this version of PHP capable of validating this email address?
$can_validate = defined('FILTER_FLAG_EMAIL_UNICODE') || strlen($url->path) == strspn(strtolower($url->path), 'abcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+-/=?^_`{|}~.@');
$flags = defined('FILTER_FLAG_EMAIL_UNICODE') ? FILTER_FLAG_EMAIL_UNICODE : null;
if (!$can_validate || filter_var($url->path, FILTER_VALIDATE_EMAIL, $flags) !== false) {
$placeholders[md5($url->path)] = $url->path;
$placeholders[md5((string) $url)] = (string) $url;
$new_string .= '[email=' . md5($url->path) . ']' . md5((string) $url) . '[/email]';
} else {
$placeholders[md5((string) $url)] = (string) $url;
$new_string .= $url;
}
continue;
}
// Are we linking a schemeless URL or naked domain name (e.g. "example.com")?
if (empty($url->scheme)) {
$full_url = new Url('//' . ltrim((string) $url, ':/'));
} else {
$full_url = clone $url;
}
// Make sure that $full_url really is valid
if (
in_array($url->scheme, self::$schemes['forbidden'])
|| (
!in_array($url->scheme, self::$schemes['no_authority'])
&& !$full_url->isValid()
)
) {
$new_string .= $url;
} elseif ((string) $full_url->toAscii() === (string) $url) {
$new_string .= '[url]' . $url . '[/url]';
} else {
$new_string .= '[url="' . str_replace(['[', ']'], ['[', ']'], (string) $full_url->toAscii()) . '"]' . $url . '[/url]';
}
}
$new_string .= substr($string, $prev_pos + $prev_len);
}
} else {
$new_string = $string;
}
if ($link_emails) {
$string = $new_string;
$detected_emails = $this->detectEmails($string, true);
if (!empty($detected_emails)) {
$new_string = '';
$prev_pos = 0;
$prev_len = 0;
foreach ($detected_emails as $pos => $email) {
$new_string .= substr($string, $prev_pos + $prev_len, $pos - ($prev_pos + $prev_len));
$prev_pos = $pos;
$prev_len = strlen($email);
$new_string .= '[email]' . $email . '[/email]';
}
$new_string .= substr($string, $prev_pos + $prev_len);
}
}
if (!empty($placeholders)) {
$new_string = strtr($new_string, $placeholders);
}
return $new_string;
}
/**
* Checks URLs inside BBCodes and fixes them if invalid.
*
* @param string $string The string containing the BBCodes.
* @return string The fixed string.
*/
public function fixUrlsInBBC(string $string): string
{
static $tags_to_fix_regex;
// In case a mod wants to add tags to the list of BBC to fix URLs in.
if (!self::$integrate_autolinker_fix_tags_done) {
IntegrationHook::call('integrate_autolinker_fix_tags', [&self::$tags_to_fix]);
self::$tags_to_fix = array_unique(self::$tags_to_fix);
self::$integrate_autolinker_fix_tags_done = true;
}
$tags_to_fix_regex = $tags_to_fix_regex ?? Utils::buildRegex((array) self::$tags_to_fix, '~');
$parts = preg_split('~(\[/?' . $tags_to_fix_regex . '\b[^\]]*\])~u', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($parts); $i < $n; $i++) {
if ($i % 4 == 1) {
unset($href, $bbc);
$bbc = substr(ltrim($parts[$i], '['), 0, strcspn(ltrim($parts[$i], '['), ' =]'));
if (str_contains($parts[$i], '=')) {
$href = substr($parts[$i], strpos($parts[$i], '=') + 1, -1);
if (str_starts_with($href, '"')) {
$href = substr($href, 6, -6);
}
if (str_starts_with($href, '"')) {
$href = substr($href, 1, -1);
}
$detected_urls = $this->detectUrls($href);
if (empty($detected_urls)) {
$parts[$i] = '';
$parts[$i + 2] = '';
continue;
}
$url = reset($detected_urls);
$parts[$i] = str_replace($href, $url, $parts[$i]);
}
} elseif ($i % 4 == 2) {
$detected_urls = $this->detectUrls($parts[$i], true);
// Not a valid URL.
if (empty($detected_urls) && empty($href)) {
$parts[$i - 1] = '';
$parts[$i + 1] = '';
continue;
}
$first_url = reset($detected_urls);
// Valid URL.
if (count($detected_urls) === 1 && $parts[$i] === $first_url) {
// BBC param is unnecessary if it is identical to the content.
if (!empty($href) && $href === $first_url) {
$parts[$i - 1] = '[' . $bbc . ']';
}
// Nothing else needs to change.
continue;
}
// One URL, plus some unexpected cruft...
if (count($detected_urls) === 1) {
foreach ($detected_urls as $url) {
if (!str_starts_with($parts[$i], $url)) {
$parts[$i - 1] = substr($parts[$i], 0, strpos($parts[$i], $url)) . $parts[$i - 1];
$parts[$i] = substr($parts[$i], strpos($parts[$i], $url));
}
if (!str_ends_with($parts[$i], $url)) {
$parts[$i + 1] .= substr($parts[$i], strlen($url));
$parts[$i] = substr($parts[$i], 0, strlen($url));
}
}
}
// Multiple URLs inside one BBCode? Weird. Fix them.
if (count($detected_urls) > 1) {
$parts[$i - 1] = '';
$parts[$i + 1] = '';
$parts[$i] = strtr(
$parts[$i],
array_combine(
$detected_urls,
array_map(fn ($url) => '[' . $bbc . ']' . $url . '[/' . $bbc . ']', $detected_urls),
),
);
}
}
}
return implode('', $parts);
}
/************************
* Public static methods.
************************/
/**
* Returns a reusable instance of this class.
*
* @param bool $only_basic If true, will only link URLs with basic TLDs.
* @return object An instance of this class.
*/
public static function load(bool $only_basic = false): object
{
if (!isset(self::$instance) || self::$instance->only_basic !== $only_basic) {
self::$instance = new self($only_basic);
}
return self::$instance;
}
/**
* Creates the JavaScript file used for autolinking in the editor.
*
* @param bool $force Whether to overwrite an existing file. Default: false.
*/
public static function createJavaScriptFile(bool $force = false): void
{
if (empty(Config::$modSettings['autoLinkUrls'])) {
return;
}
if (!isset(Theme::$current)) {
Theme::loadEssential();
}
if (!$force && file_exists(Theme::$current->settings['default_theme_dir'] . '/scripts/autolinker.js')) {
return;
}
$js[] = 'const autolinker_regexes = new Map();';
$regexes = self::load()->getJavaScriptUrlRegexes();
$regexes['email'] = self::load()->getJavaScriptEmailRegex();
foreach ($regexes as $key => $value) {
$js[] = 'autolinker_regexes.set(' . Utils::escapeJavaScript($key) . ', new RegExp(' . Utils::escapeJavaScript($value) . ', "giu"));';
$js[] = 'autolinker_regexes.set(' . Utils::escapeJavaScript('paste_' . $key) . ', new RegExp(' . Utils::escapeJavaScript('(?<=^|\s|<br>)' . $value . '(?=$|\s|<br>|[' . self::$excluded_trailing_chars . '])') . ', "giu"));';
$js[] = 'autolinker_regexes.set(' . Utils::escapeJavaScript('keypress_' . $key) . ', new RegExp(' . Utils::escapeJavaScript($value . '(?=[' . self::$excluded_trailing_chars . preg_quote(implode('', array_merge(array_keys(self::$balanced_pairs), self::$balanced_pairs)), '/') . ']*\s$)') . ', "giu"));';
}
$js[] = 'const autolinker_balanced_pairs = new Map();';
foreach (self::$balanced_pairs as $opener => $closer) {
$js[] = 'autolinker_balanced_pairs.set(' . Utils::escapeJavaScript($opener) . ', ' . Utils::escapeJavaScript($closer) . ');';
}
file_put_contents(Theme::$current->settings['default_theme_dir'] . '/scripts/autolinker.js', implode("\n", $js));
}
/*******************
* Internal methods.
*******************/
/**
* Sets $this->entities_regex.
*/
protected function setEntitiesRegex(): void
{
if (isset($this->entities_regex)) {
return;
}
$this->entities_regex = '(?' . '>&(?' . '>' . Utils::buildRegex(array_map(fn ($ent) => ltrim($ent, '&'), get_html_translation_table(HTML_ENTITIES, ENT_HTML5 | ENT_QUOTES)), '~') . '|(?' . '>#(?' . '>x[0-9a-fA-F]{1,6}|\d{1,7});)))';
}
/**
* Sets $this->tld_regex.
*/
protected function setTldRegex(): void
{
if (isset($this->tld_regex)) {
return;
}
if (!$this->only_basic && $this->encoding === 'UTF-8') {
Url::setTldRegex();
$this->tld_regex = Config::$modSettings['tld_regex'];
} else {
$this->tld_regex = Utils::buildRegex(array_merge(Url::$basic_tlds, Url::$cc_tlds, Url::$special_use_tlds));
}
}
/**
* Sets $this->js_tld_regex.
*/
protected function setJavaScriptTldRegex(): void
{
$this->setTldRegex();
// The JavaScript version of this one is simple to make.
$this->js_tld_regex = strtr($this->tld_regex, ['(?' . '>' => '(?:']);
}
/**
* Sets $this->email_regex.
*/
protected function setEmailRegex(): void
{
if (!empty($this->email_regex)) {
return;
}
$this->setTldRegex();
// Preceded by a space or start of line
$this->email_regex = '(?<=^|\s|<br>)' .
// An email address
'[' . self::$domain_label_chars . '_.]{1,80}' .
'@' .
'[' . self::$domain_label_chars . '.]+' .
'\.' . $this->tld_regex .
// Followed by a non-domain character or end of line
'(?=[^' . self::$domain_label_chars . ']|$)';
}
/**
* Sets $this->js_email_regex.
*/
protected function setJavaScriptEmailRegex(): void
{
if (!empty($this->js_email_regex)) {
return;
}
$this->setTldRegex();
// Preceded by a space or start of line
$this->js_email_regex = '(?<=^|\s|<br>)' .
// An email address
'[' . strtr(self::$domain_label_chars, ['\\x{' => '\\u{']) . '_.]{1,80}' .
'@' .
'[' . strtr(self::$domain_label_chars, ['\\x{' => '\\u{']) . '.]+' .
'\.' . strtr($this->tld_regex, ['(?' . '>' => '(?:']) .
// For JavaScript we need to use a simpler ending than the PCRE version.
'\b';
}
/**
* Sets $this->url_regex.
*/
protected function setUrlRegex(): void
{
// Don't repeat this unnecessarily.
if (!empty($this->url_regex)) {
return;
}
$this->setTldRegex();
// PCRE subroutines for efficiency.
$pcre_subroutines = [
'tlds' => $this->tld_regex,
'pct' => '%[0-9A-Fa-f]{2}',
'space_lookahead' => '(?=$|\s|<br>)',
'space_lookbehind' => '(?<=^|\s|<br>)',
'domain_label_char' => '[' . self::$domain_label_chars . ']',
'not_domain_label_char' => '[^' . self::$domain_label_chars . ']',
'domain' => '(?:(?P>domain_label_char)+\.)+(?P>tlds)(?!\.(?P>domain_label_char))',
'no_domain' => '(?:(?P>domain_label_char)|[._\\~!$&\'()*+,;=:@]|(?P>pct))+',
'scheme_need_domain' => Utils::buildRegex(self::$schemes['need_domain'], '~'),
'scheme_empty_authority' => Utils::buildRegex(self::$schemes['empty_authority'], '~'),
'scheme_no_authority' => Utils::buildRegex(self::$schemes['no_authority'], '~'),
'scheme_any' => '[A-Za-z][0-9A-Za-z+\-.]*',
'user_info' => '(?:(?P>domain_label_char)|[._\\~!$&\'()*+,;=:]|(?P>pct))+',
'dec_octet' => '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)',
'h16' => '[0-9A-Fa-f]{1,4}',
'ipv4' => '(?:\b(?:(?P>dec_octet)\.){3}(?P>dec_octet)\b)',
'ipv6' => '\[(?:' . implode('|', [
'(?:(?P>h16):){7}(?P>h16)',
'(?:(?P>h16):){1,7}:',
'(?:(?P>h16):){1,6}(?::(?P>h16))',
'(?:(?P>h16):){1,5}(?::(?P>h16)){1,2}',
'(?:(?P>h16):){1,4}(?::(?P>h16)){1,3}',
'(?:(?P>h16):){1,3}(?::(?P>h16)){1,4}',
'(?:(?P>h16):){1,2}(?::(?P>h16)){1,5}',
'(?P>h16):(?::(?P>h16)){1,6}',
':(?:(?::(?P>h16)){1,7}|:)',
'fe80:(?::(?P>h16)){0,4}%[0-9A-Za-z]+',
'::(ffff(:0{1,4})?:)?(?P>ipv4)',
'(?:(?P>h16):){1,4}:(?P>ipv4)',
]) . ')\]',
'host' => '(?:' . implode('|', [
'localhost',
'(?P>domain)',
'(?P>ipv4)',
'(?P>ipv6)',
]) . ')',
'authority' => '(?:(?P>user_info)@)?(?P>host)(?::\d+)?',
];
// Work with a fresh copy each time, in case multiple objects were instantiated.
$balanced_pairs = self::$balanced_pairs;
foreach ($balanced_pairs as $pair_opener => $pair_closer) {
$balanced_pairs[htmlspecialchars($pair_opener)] = htmlspecialchars($pair_closer);
}
$bracket_quote_chars = '';
$bracket_quote_entities = [];
foreach ($balanced_pairs as $pair_opener => $pair_closer) {
if ($pair_opener == $pair_closer) {
$pair_closer = '';
}
foreach ([$pair_opener, $pair_closer] as $bracket_quote) {
if (!str_contains($bracket_quote, '&')) {
$bracket_quote_chars .= $bracket_quote;
} else {
$bracket_quote_entities[] = substr($bracket_quote, 1);
}
}
}
$bracket_quote_chars = str_replace(['[', ']'], ['\[', '\]'], $bracket_quote_chars);
$pcre_subroutines['bracket_quote'] = '[' . $bracket_quote_chars . ']|&' . Utils::buildRegex($bracket_quote_entities, '~');
$pcre_subroutines['allowed_entities'] = '&(?!' . Utils::buildRegex(array_merge($bracket_quote_entities, ['lt;', 'gt;']), '~') . ')';
$pcre_subroutines['excluded_lookahead'] = '(?![' . self::$excluded_trailing_chars . ']*(?P>space_lookahead))';
foreach (['path', 'query', 'fragment'] as $part) {
switch ($part) {
case 'path':
$part_disallowed_chars = '\s<>' . $bracket_quote_chars . self::$excluded_trailing_chars . '/#&';
$part_excluded_trailing_chars = str_replace('?', '', self::$excluded_trailing_chars);
break;
case 'query':
$part_disallowed_chars = '\s<>' . $bracket_quote_chars . self::$excluded_trailing_chars . '#&';
$part_excluded_trailing_chars = self::$excluded_trailing_chars;
break;
default:
$part_disallowed_chars = '\s<>' . $bracket_quote_chars . self::$excluded_trailing_chars . '&';
$part_excluded_trailing_chars = self::$excluded_trailing_chars;
break;
}
$pcre_subroutines[$part . '_allowed'] = '[^' . $part_disallowed_chars . ']|(?P>allowed_entities)|[' . $part_excluded_trailing_chars . '](?P>excluded_lookahead)';
$balanced_construct_regex = [];