/
lhbbcode.php
1344 lines (1171 loc) · 56.4 KB
/
lhbbcode.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
/**
* This code is mix of WP and phpBB :)
* */
class erLhcoreClassBBCode
{
/**
* Callback to convert URI match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with URI address.
*/
public static function _make_url_clickable_cb( $matches ) {
$url = $matches[2];
$parts = explode('<',$url);
$url = array_shift($parts);
if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
// If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
// Then we can let the parenthesis balancer do its thing below.
$url .= $matches[3];
$suffix = '';
} else {
$suffix = $matches[3];
}
// Include parentheses in the URL only if paired
while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
$suffix = strrchr( $url, ')' ) . $suffix;
$url = substr( $url, 0, strrpos( $url, ')' ) );
}
$url = self::esc_url($url);
if ( empty($url) )
return $matches[0];
return $matches[1] . "<a href=\"$url\" class=\"link\" rel=\"noreferrer\" target=\"_blank\">$url</a>" . $suffix . (!empty($parts) ? '<'.implode('', $parts) : '');
}
/**
* Checks and cleans a URL.
*
* A number of characters are removed from the URL. If the URL is for displaying
* (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
* is applied to the returned cleaned URL.
*
* @since 2.8.0
*
* @param string $url The URL to be cleaned.
* @param array $protocols Optional. An array of acceptable protocols.
* Defaults to return value of wp_allowed_protocols()
* @param string $_context Private. Use esc_url_raw() for database usage.
* @return string The cleaned $url after the {@see 'clean_url'} filter is applied.
*/
public static function esc_url( $url, $protocols = null, $_context = 'display' ) {
$original_url = $url;
if ( '' == $url )
return $url;
$url = str_replace( ' ', '%20', $url );
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);
if ( '' === $url ) {
return $url;
}
if ( 0 !== stripos( $url, 'mailto:' ) ) {
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = self::_deep_replace($strip, $url);
}
$url = str_replace(';//', '://', $url);
/* If the URL doesn't appear to contain a scheme, we
* presume it needs https:// prepended (unless a relative
* link starting with /, # or ? or a php file).
*/
if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
$url = 'https://' . $url;
// Replace ampersands and single quotes only when displaying.
if ( 'display' == $_context ) {
$url = self::wp_kses_normalize_entities( $url );
$url = str_replace( '&', '&', $url );
$url = str_replace( "'", ''', $url );
}
if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
$parsed = self::wp_parse_url( $url );
$front = '';
if ( isset( $parsed['scheme'] ) ) {
$front .= $parsed['scheme'] . '://';
} elseif ( '/' === $url[0] ) {
$front .= '//';
}
if ( isset( $parsed['user'] ) ) {
$front .= $parsed['user'];
}
if ( isset( $parsed['pass'] ) ) {
$front .= ':' . $parsed['pass'];
}
if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
$front .= '@';
}
if ( isset( $parsed['host'] ) ) {
$front .= $parsed['host'];
}
if ( isset( $parsed['port'] ) ) {
$front .= ':' . $parsed['port'];
}
$end_dirty = str_replace( $front, '', $url );
$end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
$url = str_replace( $end_dirty, $end_clean, $url );
}
if ( '/' === $url[0] ) {
$good_protocol_url = $url;
} else {
if ( ! is_array( $protocols ) )
$protocols = $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
$good_protocol_url = self::wp_kses_bad_protocol( $url, $protocols );
if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
return '';
}
/**
* Filters a string cleaned and escaped for output as a URL.
*
* @since 2.3.0
*
* @param string $good_protocol_url The cleaned URL to be returned.
* @param string $original_url The URL prior to cleaning.
* @param string $_context If 'display', replace ampersands and single quotes only.
*/
return $url;
//self::esc_url( $good_protocol_url, $original_url, $_context ); //apply_filters( 'erLhcoreClassBBCode::clean_url', $good_protocol_url, $original_url, $_context );
}
/**
* A wrapper for PHP's parse_url() function that handles consistency in the return
* values across PHP versions.
*
* PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
* schemeless and relative url's with :// in the path. This function works around
* those limitations providing a standard output on PHP 5.2~5.4+.
*
* Secondly, across various PHP versions, schemeless URLs starting containing a ":"
* in the query are being handled inconsistently. This function works around those
* differences as well.
*
* Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
* when URL parsing failed.
*
* @since 4.4.0
* @since 4.7.0 The $component parameter was added for parity with PHP's parse_url().
*
* @param string $url The URL to parse.
* @param int $component The specific component to retrieve. Use one of the PHP
* predefined constants to specify which one.
* Defaults to -1 (= return all parts as an array).
* @see http://php.net/manual/en/function.parse-url.php
* @return mixed False on parse failure; Array of URL components on success;
* When a specific component has been requested: null if the component
* doesn't exist in the given URL; a string or - in the case of
* PHP_URL_PORT - integer when it does. See parse_url()'s return values.
*/
public static function wp_parse_url( $url, $component = -1 ) {
$to_unset = array();
$url = strval( $url );
if ( '//' === substr( $url, 0, 2 ) ) {
$to_unset[] = 'scheme';
$url = 'placeholder:' . $url;
} elseif ( '/' === substr( $url, 0, 1 ) ) {
$to_unset[] = 'scheme';
$to_unset[] = 'host';
$url = 'placeholder://placeholder' . $url;
}
$parts = @parse_url( $url );
if ( false === $parts ) {
// Parsing failure.
return $parts;
}
// Remove the placeholder values.
foreach ( $to_unset as $key ) {
unset( $parts[ $key ] );
}
return self::_get_component_from_parsed_url_array( $parts, $component );
}
/**
* Retrieve a specific component from a parsed URL array.
*
* @internal
*
* @since 4.7.0
*
* @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
* @param int $component The specific component to retrieve. Use one of the PHP
* predefined constants to specify which one.
* Defaults to -1 (= return all parts as an array).
* @see http://php.net/manual/en/function.parse-url.php
* @return mixed False on parse failure; Array of URL components on success;
* When a specific component has been requested: null if the component
* doesn't exist in the given URL; a string or - in the case of
* PHP_URL_PORT - integer when it does. See parse_url()'s return values.
*/
public static function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
if ( -1 === $component ) {
return $url_parts;
}
$key = self::_wp_translate_php_url_constant_to_key( $component );
if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
return $url_parts[ $key ];
} else {
return null;
}
}
/**
* Translate a PHP_URL_* constant to the named array keys PHP uses.
*
* @internal
*
* @since 4.7.0
*
* @see http://php.net/manual/en/url.constants.php
*
* @param int $constant PHP_URL_* constant.
* @return string|bool The named key or false.
*/
public static function _wp_translate_php_url_constant_to_key( $constant ) {
$translation = array(
PHP_URL_SCHEME => 'scheme',
PHP_URL_HOST => 'host',
PHP_URL_PORT => 'port',
PHP_URL_USER => 'user',
PHP_URL_PASS => 'pass',
PHP_URL_PATH => 'path',
PHP_URL_QUERY => 'query',
PHP_URL_FRAGMENT => 'fragment',
);
if ( isset( $translation[ $constant ] ) ) {
return $translation[ $constant ];
} else {
return false;
}
}
/**
* Converts and fixes HTML entities.
*
* This function normalizes HTML entities. It will convert `AT&T` to the correct
* `AT&T`, `:` to `:`, `&#XYZZY;` to `&#XYZZY;` and so on.
*
* @since 1.0.0
*
* @param string $string Content to normalize entities
* @return string Content with normalized entities
*/
public static function wp_kses_normalize_entities($string) {
// Disarm all entities by converting & to &
$string = str_replace('&', '&', $string);
// Change back the allowed entities in our entity whitelist
$string = preg_replace_callback('/&([A-Za-z]{2,8}[0-9]{0,2});/', 'erLhcoreClassBBCode::wp_kses_named_entities', $string);
$string = preg_replace_callback('/&#(0*[0-9]{1,7});/', 'erLhcoreClassBBCode::wp_kses_normalize_entities2', $string);
$string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', 'erLhcoreClassBBCode::wp_kses_normalize_entities3', $string);
return $string;
}
/**
* Callback for wp_kses_normalize_entities() for regular expression.
*
* This function helps wp_kses_normalize_entities() to only accept valid Unicode
* numeric entities in hex form.
*
* @since 2.7.0
* @access private
*
* @param array $matches preg_replace_callback() matches array
* @return string Correctly encoded entity
*/
public static function wp_kses_normalize_entities3($matches) {
if ( empty($matches[1]) )
return '';
$hexchars = $matches[1];
return ( ! self::valid_unicode( hexdec( $hexchars ) ) ) ? "&#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';';
}
/**
* Helper function to determine if a Unicode value is valid.
*
* @since 2.7.0
*
* @param int $i Unicode value
* @return bool True if the value was a valid Unicode number
*/
public static function valid_unicode($i) {
return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
($i >= 0x20 && $i <= 0xd7ff) ||
($i >= 0xe000 && $i <= 0xfffd) ||
($i >= 0x10000 && $i <= 0x10ffff) );
}
/**
* Callback for wp_kses_normalize_entities() regular expression.
*
* This function helps wp_kses_normalize_entities() to only accept 16-bit
* values and nothing more for `&#number;` entities.
*
* @access private
* @since 1.0.0
*
* @param array $matches preg_replace_callback() matches array
* @return string Correctly encoded entity
*/
public static function wp_kses_normalize_entities2($matches) {
if ( empty($matches[1]) )
return '';
$i = $matches[1];
if (self::valid_unicode($i)) {
$i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
$i = "&#$i;";
} else {
$i = "&#$i;";
}
return $i;
}
/**
* Callback for wp_kses_normalize_entities() regular expression.
*
* This function only accepts valid named entity references, which are finite,
* case-sensitive, and highly scrutinized by HTML and XML validators.
*
* @since 3.0.0
*
* @global array $allowedentitynames
*
* @param array $matches preg_replace_callback() matches array
* @return string Correctly encoded entity
*/
public static function wp_kses_named_entities($matches) {
$allowedentitynames = array(
'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen',
'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo',
'not', 'shy', 'reg', 'macr', 'deg', 'plusmn',
'acute', 'micro', 'para', 'middot', 'cedil', 'ordm',
'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde',
'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute',
'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml',
'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde',
'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc',
'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute',
'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil',
'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute',
'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute',
'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave',
'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml',
'quot', 'amp', 'lt', 'gt', 'apos', 'OElig',
'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde',
'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm',
'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo',
'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil',
'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta',
'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi',
'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon',
'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta',
'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',
'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym',
'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime',
'oline', 'frasl', 'weierp', 'image', 'real', 'trade',
'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr',
'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr',
'forall', 'part', 'exist', 'empty', 'nabla', 'isin',
'notin', 'ni', 'prod', 'sum', 'minus', 'lowast',
'radic', 'prop', 'infin', 'ang', 'and', 'or',
'cap', 'cup', 'int', 'sim', 'cong', 'asymp',
'ne', 'equiv', 'le', 'ge', 'sub', 'sup',
'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp',
'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang',
'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams',
'sup1', 'sup2', 'sup3', 'frac14', 'frac12', 'frac34',
'there4',
);
if ( empty($matches[1]) )
return '';
$i = $matches[1];
return ( ! in_array( $i, $allowedentitynames ) ) ? "&$i;" : "&$i;";
}
/**
* Sanitize string from bad protocols.
*
* This function removes all non-allowed protocols from the beginning of
* $string. It ignores whitespace and the case of the letters, and it does
* understand HTML entities. It does its work in a while loop, so it won't be
* fooled by a string like "javascript:javascript:alert(57)".
*
* @since 1.0.0
*
* @param string $string Content to filter bad protocols from
* @param array $allowed_protocols Allowed protocols to keep
* @return string Filtered content
*/
public static function wp_kses_bad_protocol($string, $allowed_protocols) {
$string = self::wp_kses_no_null($string);
$iterations = 0;
do {
$original_string = $string;
$string = self::wp_kses_bad_protocol_once($string, $allowed_protocols);
} while ( $original_string != $string && ++$iterations < 6 );
if ( $original_string != $string )
return '';
return $string;
}
/**
* Removes any invalid control characters in $string.
*
* Also removes any instance of the '\0' string.
*
* @since 1.0.0
*
* @param string $string
* @param array $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
* @return string
*/
public static function wp_kses_no_null( $string, $options = null ) {
if ( ! isset( $options['slash_zero'] ) ) {
$options = array( 'slash_zero' => 'remove' );
}
$string = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string );
if ( 'remove' == $options['slash_zero'] ) {
$string = preg_replace( '/\\\\+0+/', '', $string );
}
return $string;
}
/**
* Sanitizes content from bad protocols and other characters.
*
* This function searches for URL protocols at the beginning of $string, while
* handling whitespace and HTML entities.
*
* @since 1.0.0
*
* @param string $string Content to check for bad protocols
* @param string $allowed_protocols Allowed protocols
* @return string Sanitized content
*/
public static function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
$string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
$string = trim( $string2[1] );
$protocol = self::wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
if ( 'feed:' == $protocol ) {
if ( $count > 2 )
return '';
$string = self::wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
if ( empty( $string ) )
return $string;
}
$string = $protocol . $string;
}
return $string;
}
/**
* Callback for wp_kses_bad_protocol_once() regular expression.
*
* This function processes URL protocols, checks to see if they're in the
* whitelist or not, and returns different data depending on the answer.
*
* @access private
* @since 1.0.0
*
* @param string $string URI scheme to check against the whitelist
* @param string $allowed_protocols Allowed protocols
* @return string Sanitized content
*/
public static function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
$string2 = self::wp_kses_decode_entities($string);
$string2 = preg_replace('/\s/', '', $string2);
$string2 = self::wp_kses_no_null($string2);
$string2 = strtolower($string2);
$allowed = false;
foreach ( (array) $allowed_protocols as $one_protocol )
if ( strtolower($one_protocol) == $string2 ) {
$allowed = true;
break;
}
if ($allowed)
return "$string2:";
else
return '';
}
/**
* Convert all entities to their character counterparts.
*
* This function decodes numeric HTML entities (`A` and `A`).
* It doesn't do anything with other entities like ä, but we don't
* need them in the URL protocol whitelisting system anyway.
*
* @since 1.0.0
*
* @param string $string Content to change entities
* @return string Content after decoded entities
*/
public static function wp_kses_decode_entities($string) {
$string = preg_replace_callback('/&#([0-9]+);/', 'erLhcoreClassBBCode::_wp_kses_decode_entities_chr', $string);
$string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', 'erLhcoreClassBBCode::_wp_kses_decode_entities_chr_hexdec', $string);
return $string;
}
/**
* Regex callback for wp_kses_decode_entities()
*
* @since 2.9.0
*
* @param array $match preg match
* @return string
*/
public static function _wp_kses_decode_entities_chr( $match ) {
return chr( $match[1] );
}
/**
* Regex callback for wp_kses_decode_entities()
*
* @since 2.9.0
*
* @param array $match preg match
* @return string
*/
public static function _wp_kses_decode_entities_chr_hexdec( $match ) {
return chr( hexdec( $match[1] ) );
}
/**
* Perform a deep string replace operation to ensure the values in $search are no longer present
*
* Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
* e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
* str_replace would return
*
* @since 2.8.1
* @access private
*
* @param string|array $search The value being searched for, otherwise known as the needle.
* An array may be used to designate multiple needles.
* @param string $subject The string being searched and replaced on, otherwise known as the haystack.
* @return string The string with the replaced svalues.
*/
public static function _deep_replace( $search, $subject ) {
$subject = (string) $subject;
$count = 1;
while ( $count ) {
$subject = str_replace( $search, '', $subject, $count );
}
return $subject;
}
public static $replaceEmoji = array(
':\)' => "\u{1F642}",
':D:' => "\u{1F600}",
':D' => "\u{1F600}",
':\(' => "\u{1F641}",
':o:' => "\u{1F62E}",
':o' => "\u{1F62E}",
':p:' => "\u{1F61B}",
':p' => "\u{1F61B}",
';\)' => "\u{1F609}",
';\(' => "\u{1F622}",
':x' => "\u{1F910}",
':\*' => "\u{1F617}",
';\*' => "\u{1F618}",
':\/' => "\u{1F615}"
);
public static function parseEmoji($text) {
// Smileys to find...
for ($i = 0; $i < 2; $i++) {
$text = preg_replace_callback('/(^|\s)(' .implode("|",array_keys(self::$replaceEmoji)) . ')(\s|$)/', function($match) {
$char = str_replace(array('/','(',')','*'),array('\/','\(','\)','\*'),$match[2]);
return $match[1] . erLhcoreClassBBCode::$replaceEmoji[$char] . $match[3];
}, $text);
}
return $text;
}
public static function BBCode2Html($text, $paramsMessage = []) {
$text = trim($text);
$text = self::parseEmoji($text);
// Smileys to find...
$in = array(
);
// And replace them by...
$out = array(
);
if (self::isBBCodeTagSupported('[li]', $paramsMessage)) {
$in[] = '[/*]';
$in[] = '[*]';
$out[] = '</li>';
$out[] = '<li>';
$text = str_replace($in, $out, $text);
}
// BBCode to find...
$in = array( '/\[b\](.*?)\[\/b\]/ms' => '[b]',
'/\[i\](.*?)\[\/i\]/ms' => '[i]',
'/\[u\](.*?)\[\/u\]/ms' => '[u]',
'/\[mark\](.*?)\[\/mark\]/ms' => '[mark]',
'/\[s\](.*?)\[\/s\]/ms' => '[s]',
'/\[list\=([0-9]+)\](.*?)\[\/list\]/ms' => '[listol]',
'/\[list\](.*?)\[\/list\]/ms' => '[list]',
'/\[\*\]\s?(.*?)\n/ms' => '[li]',
'/\[fs([0-9]+)\](.*?)\[\/fs\]/ms' => '[fs12]',
'/\[color\=([A-Za-z0-9]{2,6})\](.*?)\[\/color\]/ms' => '[color]',
'/\[level\=([A-Za-z0-9\-\s]{2,60})\](.*?)\[\/level\]/ms' => '[level]'
);
// And replace them by...
$out = array( '[b]' => '<strong>\1</strong>',
'[i]' => '<em>\1</em>',
'[u]' => '<u>\1</u>',
'[mark]' => '<mark>\1</mark>',
'[s]' => '<strike>\1</strike>',
'[listol]' => '<ol class="default-list" start="\1">\2</ol>',
'[list]' => '<ul class="default-list" >\1</ul>',
'[li]' => '<li>\1</li>',
'[fs12]' => '<span style="font-size:\1pt">\2</span>',
'[color]' => '<span style="color:#\1">\2</span>',
'[level]' => '<span class="\1">\2</span>'
);
$filteredBBCode = ['search' => [],'replace' => []];
foreach ($in as $matchRule => $bbCode) {
if (self::isBBCodeTagSupported($bbCode, $paramsMessage)) {
$filteredBBCode['search'][] = $matchRule;
$filteredBBCode['replace'][] = $out[$bbCode];
}
}
$text = preg_replace($filteredBBCode['search'], $filteredBBCode['replace'], $text);
// Prepare quote's
$text = str_replace("\r\n","\n",$text);
// paragraphs
$text = str_replace("\r", "", $text);
$text = nl2br($text);
// clean some tags to remain strict
// not very elegant, but it works. No time to do better ;)
if (!function_exists('removeBr')) {
function removeBr($s) {
return str_replace("<br />", "", $s[0]);
}
}
$text = preg_replace_callback('/<pre>(.*?)<\/pre>/ms', "removeBr", $text);
$text = preg_replace_callback('/<code>(.*?)<\/code>/ms', "removeBr", $text);
$text = preg_replace('/<p><pre>(.*?)<\/pre><\/p>/ms', "<pre>\\1</pre>", $text);
$text = preg_replace_callback('/<ul>(.*?)<\/ul>/ms', "removeBr", $text);
$text = preg_replace('/<p><ul>(.*?)<\/ul><\/p>/ms', "<ul>\\1</ul>", $text);
return $text;
}
public static function _make_url_embed_image($matches) {
$in = htmlspecialchars_decode($matches[2]);
$in = trim($in);
$url = self::esc_url($in);
if ( empty($url) )
return '[img]' . $matches[2] . '[img]';
$prepend = '';
$append = '';
if (isset($matches[1]) && $matches[1] != '' && !empty(self::esc_url($matches[1]))) {
$prepend = '<a class="link" rel="noreferrer" target="_blank" href="' . $matches[1] . '">';
$append = '</a>';
}
return "<div class=\"img_embed\">{$prepend}<img title=\"\" onclick='lhinst.zoomImage(this)' class='action-image img-fluid img-remote' src=\"".$url."\" alt=\"\" />{$append}</div>";
}
public static function _make_embed_map($matches)
{
$parts = explode(',',trim($matches[1]));
if (count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
$id = rand(0,1000) . time();
return "<div id='msg-location-".$id."' style='height:300px'><script>lhinst.showMessageLocation(" . $id . "," . (float)$parts[0] . "," . (float)$parts[1] . ")</script></div>";
}
return ;
}
public static function _make_url_embed($matches){
$in = str_replace('"','',htmlspecialchars_decode($matches[1]));
$in = trim($in);
$url = self::esc_url($in);
if ( empty($url) )
return '[url='.$matches[1].']' . $matches[2] . '[/url]';
return '<a class="link" target="_blank" rel="noreferrer" href="'.$url.'">' . $matches[2] . '</a>';
}
public static function _make_code($matches){
return '<pre class="blockquote blockquote-code"><code>'.trim($matches[1]).'</code></pre>';
}
/**
* Callback to convert URL match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with URL address.
*/
public static function _make_web_ftp_clickable_cb( $matches ) {
$ret = '';
$dest = $matches[2];
$dest = 'https://' . $dest;
// removed trailing [.,;:)] from URL
if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
$dest = self::esc_url($dest);
if ( empty($dest) )
return $matches[0];
return $matches[1] . "<a href=\"$dest\" class=\"link\" rel=\"noreferrer\" target=\"_blank\">$dest</a>$ret";
}
/**
* Callback to convert email address match to HTML A element.
*
* This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
*
* @since 2.3.2
* @access private
*
* @param array $matches Single Regex Match.
* @return string HTML A element with email address.
*/
public static function _make_email_clickable_cb( $matches ) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a rel=\"noreferrer\" target=\"_blank\" class=\"link\" href=\"mailto:$email\">$email</a>";
}
public static function _make_paypal_button($matches){
if (filter_var($matches[1],FILTER_VALIDATE_EMAIL)) {
return '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="'.$matches[1].'">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-DonationsBF:btn_donate_SM.gif:NonHostedGuest">
<input type="image" title="Support an artist" src="https://www.paypalobjects.com/WEBSCR-640-20110306-1/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/WEBSCR-640-20110306-1/en_US/i/scr/pixel.gif" width="1" height="1">
</form>';
} else {
return $matches[0];
}
}
public static function _make_button_action($matches) {
return "<button type=\"button\" class=\"btn btn-xs text-white fs13 btn-secondary\" onclick=\"lhinst.buttonAction($(this),'" . htmlspecialchars(strip_tags($matches[1])) . "')\">" . htmlspecialchars($matches[2]) . "</button>";
}
public static function _make_link_trigger($matches) {
return "<a class=\"action-image link-trigger-button\" data-id=\"{msg_id}\" data-payload=\"".htmlspecialchars(strip_tags($matches[1]))."\" onclick='lhinst.updateTriggerClicked(\"".htmlspecialchars(strip_tags($matches[1]))."\",{msg_id},$(this))'>" . htmlspecialchars($matches[2]) . "</a>";
}
public static function _make_youtube_block($matches) {
$data = parse_url($matches[1]);
if (isset($data['query'])){
parse_str($data['query'],$query);
if (stristr($data['host'],'youtube.com') && isset($query['v']) && ($query['v'] != '')) {
return '<iframe class="w-100 h-100" title="YouTube video player" width="480" height="300" src="https://www.youtube.com/embed/'.urlencode($query['v']).'" frameborder="0" allowfullscreen></iframe>';
} else {
return $matches[0];
}
} else {
return $matches[0];
}
}
public static function getHost() {
return erLhcoreClassSystem::getHost();
}
public static function _make_upload_link($matches){
$data = $matches[1];
return '<a class="action-image alert-link" onclick="lhinst.chooseFile()">' . htmlspecialchars($data) . '</a>';
}
public static function _make_base_link($matches) {
$data = htmlspecialchars($matches[1]);
$url = self::getHost() . erLhcoreClassDesign::baseurl($data);
return $url;
}
public static function _make_url_file($matches)
{
if (isset($matches[1])){
$mainData = explode(' ',$matches[1]);
$parts = explode('_',$mainData[0]);
$fileID = $parts[0];
$hash = $parts[1];
$displayType = isset($parts[2]) ? $parts[2] : null;
try {
$file = erLhcoreClassModelChatFile::fetch($fileID);
if (is_object($file)) {
// Check that user has permission to see the chat. Let say if user purposely types file bbcode
if ($hash == $file->security_hash) {
$fileExtension = strtolower($file->extension);
if (in_array($fileExtension,['jfif','jpg','jpeg','png','gif','webp'])){
// Make link if required
$prepend = '';
$append = '';
if (isset($mainData[1])) {
$subpartParts = explode('=',$mainData[1]);
if ($subpartParts[0] == 'link' || $subpartParts[0] == 'linkdirect') {
if (!isset($subpartParts[1])) {
$prepend = '<a class="link" rel="noreferrer" target="_blank" href="'. self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}/(inline)/true\">";
$append = '</a>';
if ($subpartParts[0] == 'linkdirect') {
return"<a href=\"" . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}\" target=\"_blank\" rel=\"noreferrer\" class=\"link\" >" . erTranslationClassLhTranslation::getInstance()->getTranslation('file/file', 'Download file') . ' - ' . htmlspecialchars($file->upload_name) . ' [' . $file->extension . ']' . "</a>";
}
} else {
$url = self::esc_url($subpartParts[1]);
if ($url != ''){
$prepend = '<a class="link" rel="noreferrer" target="_blank" href="' . self::esc_url($subpartParts[1]) . '">';
$append = '</a>';
}
}
}
} else {
$prepend = '<div class="position-relative">';
$append = '<a class="hidden-download" target="_blank" rel="noreferrer" href="'. self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}".'/(inline)/true"></a></div>';
}
$imageSizeAttr = '';
if (in_array($fileExtension,['jpg','jpeg','png'])) {
list($width, $height) = getimagesize($file->file_path_server);
if ($width > 0 && $height > 0 && $width < 10000 && $height < 10000) {
$imageSizeAttr = ' width="'.(int)$width.'" height="'.(int)$height.'" ';
}
}
if (isset($displayType) && $displayType == 'rawimg') {
return '<img onclick="lhinst.zoomImage(this)" '.$imageSizeAttr.' id="img-file-' . $file->id . '" title="'.htmlspecialchars($file->upload_name).'" class="action-image img-fluid" src="' . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}" . '" alt="'.htmlspecialchars($file->upload_name).'" />';
} else {
return $prepend . '<img onclick="lhinst.zoomImage(this)" '.$imageSizeAttr.' id="img-file-' . $file->id . '" title="'.htmlspecialchars($file->upload_name).'" class="action-image img-fluid" src="' . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}" . '" alt="'.htmlspecialchars($file->upload_name).'" />' . $append;
}
}
$audio = '';
if (in_array($fileExtension,['mp3','wav','ogg','oga'])) {
return '<a rel="noreferrer" class="hidden-download audio-download" href="'. self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}".'"></a><audio preload="none" style="width: 230px" controls><source src="' . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}" . '" type="' . $file->type . '"></audio>';
} elseif (in_array($fileExtension,['mp4','avi','mov','ogg','3gpp'])) {
$audio = '<br><div class="embed-responsive embed-responsive-16by9"><video class="embed-responsive-item" controls><source src="' . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}" . '"></video></div>';
}
return "<a href=\"" . self::getHost() . erLhcoreClassDesign::baseurl('file/downloadfile') . "/{$file->id}/{$hash}\" target=\"_blank\" rel=\"noreferrer\" class=\"link\" >" . erTranslationClassLhTranslation::getInstance()->getTranslation('file/file', 'Download file') . ' - ' . htmlspecialchars($file->upload_name) . ' [' . $file->extension . ']' . "</a>" . $audio;
}
}
} catch (Exception $e) {
}
return '';
}
return '';
}
public static function _make_url_survey($matches)
{
if (isset($matches[1])){
list($surveyId, $surveyItemId) = explode('_',str_replace(array('"','"'),'', $matches[1]));
try {
if (is_numeric($surveyItemId) && is_numeric($surveyId)) {
$surveyItem = erLhAbstractModelSurveyItem::fetch($surveyItemId);
if ($surveyId == $surveyItem->survey_id)
{
$survey = erLhAbstractModelSurvey::fetch($surveyId);
return "<a href=\"" . self::getHost() . erLhcoreClassDesign::baseurl('survey/collected')."/{$survey->id}?show={$surveyItem->id}\" target=\"_blank\" rel=\"noreferrer\" class=\"link\" >" . erTranslationClassLhTranslation::getInstance()->getTranslation('file/file','Collected survey data') . ' - ' . htmlspecialchars($survey->name) . "</a>";
}
}
} catch (Exception $e) {
}
return '';
}
return '';
}
public static function _make_url_mail_file($matches){
if (isset($matches[1])){
list($fileID,$hash) = explode('_',$matches[1]);
try {
$file = erLhcoreClassModelChatFile::fetch($fileID);
// Check that user has permission to see the chat. Let say if user purposely types file bbcode
if ($hash == $file->security_hash) {
return self::getHost() . erLhcoreClassDesign::baseurldirect('file/downloadfile')."/{$file->id}/{$hash}";
}
} catch (Exception $e) {
}
return '';
}
return '';
}
public static function _split_str_by_whitespace( $string, $goal ) {
$chunks = array();
$string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
while ( $goal < strlen( $string_nullspace ) ) {
$pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
if ( false === $pos ) {
$pos = strpos( $string_nullspace, "\000", $goal + 1 );
if ( false === $pos ) {
break;
}
}
$chunks[] = substr( $string, 0, $pos + 1 );
$string = substr( $string, $pos + 1 );
$string_nullspace = substr( $string_nullspace, $pos + 1 );
}
if ( $string ) {
$chunks[] = $string;
}
return $chunks;
}
// https://github.com/WordPress/WordPress/blob/6e5e29c5bf49ad2be6a2c3a3d4fb3f5af6853b5b/wp-includes/formatting.php
public static function make_clickable_text( $text ) {
$r = '';
$textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
$nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
foreach ( $textarr as $piece ) {
if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) )
$nested_code_pre++;
elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) )
$nested_code_pre--;
if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
$r .= $piece;
continue;