-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathHtml.php
More file actions
1275 lines (1144 loc) · 45.3 KB
/
Html.php
File metadata and controls
1275 lines (1144 loc) · 45.3 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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use Craft;
use craft\elements\Asset;
use craft\errors\InvalidHtmlTagException;
use craft\image\SvgAllowedAttributes;
use craft\web\View;
use DOMElement;
use enshrined\svgSanitize\Sanitizer;
use Symfony\Component\DomCrawler\Crawler;
use Throwable;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
/**
* Class Html
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Html extends \yii\helpers\Html
{
/**
* @since 5.6.0
*/
public const TITLE_TAG_RE = '/<title(\s+([\s\S]*?))?>.*?<\/title>\s*/is';
/**
* @var array List of tag attributes that should be specially handled when their values are of array type.
* In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
* will be generated instead of one: `data-name="xyz" data-age="13"`.
* @since 4.0.0
*/
public static $dataAttributes = [
'aria',
'data',
'data-hx',
'data-ng',
'hx',
'ng',
];
/**
* @var string[]
* @see _sortedDataAttributes()
*/
private static array $_sortedDataAttributes;
/**
* Will take an HTML string and an associative array of key=>value pairs, HTML encode the values and swap them back
* into the original string using the keys as tokens.
*
* @param string $html The HTML string.
* @param array $variables An associative array of key => value pairs to be applied to the HTML string using `strtr`.
* @return string The HTML string with the encoded variable values swapped in.
*/
public static function encodeParams(string $html, array $variables = []): string
{
// Normalize the param keys
$normalizedVariables = [];
foreach ($variables as $key => $value) {
$key = '{' . trim($key, '{}') . '}';
$normalizedVariables[$key] = static::encode($value);
}
return strtr($html, $normalizedVariables);
}
/**
* Converts spaces into `%20` entities.
*
* @param string $str
* @return string
* @since 4.0.4
*/
public static function encodeSpaces(string $str): string
{
return str_replace(' ', '%20', $str);
}
/**
* Disables any form inputs in the given HTML.
*
* @param callable|string|null $html
* @return string|null
* @since 5.6.0
*/
public static function disableInputs(callable|string|null $html): ?string
{
if (is_callable($html)) {
// Call it to get the HTML, but disregard the JS
Craft::$app->getView()->startJsBuffer();
try {
$html = $html();
} finally {
Craft::$app->getView()->clearJsBuffer();
}
}
if ($html === null || $html === '') {
return $html;
}
$crawler = new Crawler("<html><body>$html</body></html>");
$inputContainers = $crawler->filter('.field > .input');
foreach ($inputContainers as $inputContainer) {
/** @var DOMElement $inputContainer */
$class = array_filter(explode(' ', $inputContainer->getAttribute('class')));
$class = array_unique([...$class, 'disabled']);
$inputContainer->setAttribute('class', implode(' ', $class));
}
$inputs = $crawler->filter('input,textarea,select,button:not(.fieldtoggle)');
foreach ($inputs as $input) {
/** @var DOMElement $input */
if (!$input->hasAttribute('disabled')) {
$input->setAttribute('disabled', '');
}
}
return $crawler->filter('body')->first()->html();
}
/**
* Generates a hidden CSRF input tag.
*
* @param array $options The tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string The generated hidden input tag
* @since 3.3.0
*/
public static function csrfInput(array $options = []): string
{
$request = Craft::$app->getRequest();
$async = ArrayHelper::remove($options, 'async')
?? ($request->getIsSiteRequest() && Craft::$app->getConfig()->getGeneral()->asyncCsrfInputs);
if (!$async) {
Craft::$app->getResponse()->setNoCacheHeaders();
return static::hiddenInput($request->csrfParam, $request->getCsrfToken(), $options);
}
Craft::$app->getView()->registerHtml(
Craft::$app->getView()->renderTemplate(
'_special/async-csrf-input',
[
'url' => UrlHelper::actionUrl('users/session-info'),
],
View::TEMPLATE_MODE_CP,
)
);
return static::tag('craft-csrf-input');
}
/**
* @inheritdoc
*/
public static function beginForm($action = '', $method = 'post', $options = []): string
{
if (!isset($options['accept-charset'])) {
$options['accept-charset'] = 'UTF-8';
}
return parent::beginForm($action, $method, $options);
}
/**
* Generates a hidden `action` input tag.
*
* @param string $route The action route
* @param array $options The tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string The generated hidden input tag
* @since 3.3.0
*/
public static function actionInput(string $route, array $options = []): string
{
return static::hiddenInput('action', $route, $options);
}
/**
* Generates a hidden `redirect` input tag.
*
* @param string $url The URL to redirect to
* @param array $options The tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string The generated hidden input tag
* @throws Exception if the validation key could not be written
* @throws InvalidConfigException when HMAC generation fails
* @since 3.3.0
*/
public static function redirectInput(string $url, array $options = []): string
{
return static::hiddenInput('redirect', Craft::$app->getSecurity()->hashData($url), $options);
}
/**
* Generates a hidden `failMessage` input tag.
*
* @param string $message The flash message to shown on failure
* @param array $options The tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string The generated hidden input tag
* @throws Exception if the validation key could not be written
* @throws InvalidConfigException when HMAC generation fails
* @since 3.6.6
*/
public static function failMessageInput(string $message, array $options = []): string
{
return static::hiddenInput('failMessage', Craft::$app->getSecurity()->hashData($message), $options);
}
/**
* Generates a hidden `successMessage` input tag.
*
* @param string $message The flash message to shown on success
* @param array $options The tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string The generated hidden input tag
* @throws Exception if the validation key could not be written
* @throws InvalidConfigException when HMAC generation fails
* @since 3.6.6
*/
public static function successMessageInput(string $message, array $options = []): string
{
return static::hiddenInput('successMessage', Craft::$app->getSecurity()->hashData($message), $options);
}
/**
* @inheritdoc
*/
public static function tag($name, $content = '', $options = [])
{
return parent::tag($name, $content, static::normalizeTagAttributes($options));
}
/**
* @inheritdoc
*/
public static function beginTag($name, $options = [])
{
return parent::beginTag($name, static::normalizeTagAttributes($options));
}
/**
* @inheritdoc
* @since 3.3.0
*/
public static function a($text, $url = null, $options = []): string
{
if ($url !== null) {
// Use UrlHelper::url() instead of Url::to()
$options['href'] = UrlHelper::url($url);
}
return static::tag('a', $text, $options);
}
/**
* Appends HTML to the end of the given tag.
*
* @param string $tag The HTML tag that `$html` should be appended to
* @param string $html The HTML to append to `$tag`.
* @param string|null $ifExists What to do if `$tag` already contains a child of the same type as the element
* defined by `$html`. Set to `'keep'` if no action should be taken, or `'replace'` if it should be replaced
* by `$tag`.
* @return string The modified HTML
* @since 3.3.0
*/
public static function appendToTag(string $tag, string $html, ?string $ifExists = null): string
{
return self::_addToTagInternal($tag, $html, 'htmlEnd', $ifExists);
}
/**
* Prepends HTML to the beginning of given tag.
*
* @param string $tag The HTML tag that `$html` should be prepended to
* @param string $html The HTML to prepend to `$tag`.
* @param string|null $ifExists What to do if `$tag` already contains a child of the same type as the element
* defined by `$html`. Set to `'keep'` if no action should be taken, or `'replace'` if it should be replaced
* by `$tag`.
* @return string The modified HTML
* @since 3.3.0
*/
public static function prependToTag(string $tag, string $html, ?string $ifExists = null): string
{
return self::_addToTagInternal($tag, $html, 'htmlStart', $ifExists);
}
/**
* Parses an HTML tag and returns info about it and its children.
*
* @param string $tag The HTML tag
* @param int $offset The offset to start looking for a tag
* @return array An array containing `type`, `attributes`, `children`, `start`, `end`, `htmlStart`, and `htmlEnd`
* properties. Nested text nodes will be represented as arrays within `children` with `type` set to `'text'`, and a
* `value` key containing the text value.
* @throws InvalidHtmlTagException if `$tag` doesn't contain a valid HTML tag
* @since 3.3.0
*/
public static function parseTag(string $tag, int $offset = 0): array
{
[$type, $start] = self::_findTag($tag, $offset);
$attributes = static::parseTagAttributes($tag, $start, $attrStart, $attrEnd);
$end = strpos($tag, '>', $attrEnd) + 1;
$isVoid = $tag[$end - 2] === '/' || isset(static::$voidElements[$type]);
$children = [];
// If this is a void element, we're done here
if ($isVoid) {
$htmlStart = $htmlEnd = null;
} else {
// Otherwise look for nested tags
$htmlStart = $cursor = $end;
if (!in_array($type, ['script', 'style'])) {
do {
try {
$subtag = static::parseTag($tag, $cursor);
// Did we skip some text to get there?
if ($subtag['start'] > $cursor) {
$children[] = [
'type' => 'text',
'value' => substr($tag, $cursor, $subtag['start'] - $cursor),
];
}
$children[] = $subtag;
$cursor = $subtag['end'];
} catch (InvalidHtmlTagException) {
// We must have just reached the end
break;
}
} while (true);
}
// Find the closing tag
if (($htmlEnd = stripos($tag, "</$type>", $cursor)) === false) {
throw new InvalidHtmlTagException("Could not find a </$type> tag in string: $tag", $type, $attributes, $start, $htmlStart);
}
$end = $htmlEnd + strlen($type) + 3;
if ($htmlEnd > $cursor) {
$children[] = [
'type' => 'text',
'value' => substr($tag, $cursor, $htmlEnd - $cursor),
];
}
}
return compact('type', 'attributes', 'children', 'start', 'htmlStart', 'htmlEnd', 'end');
}
/**
* Modifies a HTML tag’s attributes, supporting the same attribute definitions as [[renderTagAttributes()]].
*
* @param string $tag The HTML tag whose attributes should be modified.
* @param array $attributes The attributes to be added to the tag.
* @return string The modified HTML tag.
* @throws InvalidArgumentException if `$tag` doesn't contain a valid HTML tag
* @since 3.3.0
*/
public static function modifyTagAttributes(string $tag, array $attributes): string
{
// Normalize the attributes & merge with the old attributes
$attributes = static::normalizeTagAttributes($attributes);
$oldAttributes = static::parseTagAttributes($tag, 0, $start, $end, true);
$attributes = ArrayHelper::merge($oldAttributes, $attributes);
// Ensure we don't have any duplicate classes
if (isset($attributes['class']) && is_array($attributes['class'])) {
$attributes['class'] = array_unique($attributes['class']);
}
return substr($tag, 0, $start) .
static::renderTagAttributes($attributes) .
substr($tag, $end);
}
/**
* Parses an HTML tag to find its attributes.
*
* @param string $tag The HTML tag to parse
* @param int $offset The offset to start looking for a tag
* @param int|null $start The start position of the first attribute in the given tag
* @param-out int $start
* @param int|null $end The end position of the last attribute in the given tag
* @param bool $decode Whether the attributes should be HTML decoded in the process
* @return array The parsed HTML tag attributes
* @throws InvalidHtmlTagException if `$tag` doesn't contain a valid HTML tag
* @since 3.3.0
*/
public static function parseTagAttributes(string $tag, int $offset = 0, ?int &$start = null, ?int &$end = null, bool $decode = false): array
{
[$type, $tagStart] = self::_findTag($tag, $offset);
$start = $tagStart + strlen($type) + 1;
$anchor = $start;
$attributes = [];
do {
try {
$attribute = static::parseTagAttribute($tag, $anchor, $attrStart, $attrEnd);
} catch (InvalidArgumentException $e) {
throw new InvalidHtmlTagException($e->getMessage(), $type, null, $tagStart);
}
// Did we just reach the end of the tag?
if ($attribute === null) {
$end = $anchor;
break;
}
[$name, $value] = $attribute;
$attributes[$name] = $value;
$anchor = $attrEnd;
} while (true);
$attributes = static::normalizeTagAttributes($attributes);
if ($decode) {
foreach ($attributes as &$value) {
if (is_string($value)) {
$value = static::decode($value);
}
}
}
return $attributes;
}
/**
* Parses the next HTML tag attribute in a given string.
*
* @param string $html The HTML to parse
* @param int $offset The offset to start looking for an attribute
* @param int|null $start The start position of the attribute in the given HTML
* @param int|null $end The end position of the attribute in the given HTML
* @return array|null The name and value of the attribute, or `false` if no complete attribute was found
* @throws InvalidArgumentException if `$html` doesn't begin with a valid HTML attribute
* @since 3.7.0
*/
public static function parseTagAttribute(string $html, int $offset = 0, ?int &$start = null, ?int &$end = null): ?array
{
if (!preg_match('/\s*([^=\/>\s]+)/A', $html, $match, PREG_OFFSET_CAPTURE, $offset)) {
if (!preg_match('/(\s*)\/?>/A', $html, $m, 0, $offset)) {
// No `>`
throw new InvalidArgumentException("Malformed HTML tag attribute in string: $html");
}
// No more attributes here
return null;
}
$value = true;
// Does the tag have an explicit value?
$offset += strlen($match[0][0]);
if (preg_match('/\s*=\s*/A', $html, $m, 0, $offset)) {
$offset += strlen($m[0]);
// Wrapped in quotes?
if (isset($html[$offset]) && in_array($html[$offset], ['\'', '"'])) {
$q = preg_quote($html[$offset], '/');
if (!preg_match("/$q(.*?)$q/sA", $html, $m, 0, $offset)) {
// No matching end quote
throw new InvalidArgumentException("Malformed HTML tag attribute in string: $html");
}
$offset += strlen($m[0]);
if (isset($m[1]) && $m[1] !== '') {
$value = static::decode($m[1]);
}
} elseif (preg_match('/[^\s>]+/A', $html, $m, 0, $offset)) {
$offset += strlen($m[0]);
$value = static::decode($m[0]);
}
}
$start = (int) $match[1][1];
$end = $offset;
return [$match[1][0], $value];
}
/**
* Normalizes attributes.
*
* @param array $attributes
* @return array
* @since 3.3.0
*/
public static function normalizeTagAttributes(array $attributes): array
{
$normalized = [];
foreach ($attributes as $name => $value) {
if ($value === false || $value === null) {
$normalized[$name] = false;
continue;
}
switch ($name) {
case 'class':
case 'removeClass':
$normalized[$name] = static::explodeClass($value);
break;
case 'style':
$normalized[$name] = static::explodeStyle($value);
break;
default:
// See if it's a data attribute
foreach (self::_sortedDataAttributes() as $dataAttribute) {
if (str_starts_with($name, $dataAttribute . '-')) {
$n = substr($name, strlen($dataAttribute) + 1);
$normalized[$dataAttribute][$n] = $value;
break 2;
}
}
$normalized[$name] = $value;
}
}
if (isset($normalized['removeClass'])) {
$removeClasses = ArrayHelper::remove($normalized, 'removeClass');
$normalized['class'] = array_diff($normalized['class'] ?? [], $removeClasses);
}
return $normalized;
}
/**
* Explodes a `class` attribute into an array.
*
* @param mixed $value
* @return string[]
* @since 3.5.0
*/
public static function explodeClass(mixed $value): array
{
if ($value === null || is_bool($value)) {
return [];
}
if (is_array($value)) {
return $value;
}
if (is_string($value)) {
return ArrayHelper::filterEmptyStringsFromArray(explode(' ', $value));
}
throw new InvalidArgumentException('Invalid class value');
}
/**
* Explodes a `style` attribute into an array of property/value pairs.
*
* @param mixed $value
* @return string[]
* @since 3.5.0
*/
public static function explodeStyle(mixed $value): array
{
if ($value === null || is_bool($value)) {
return [];
}
if (is_array($value)) {
return $value;
}
if (is_string($value)) {
// first match any css properties that contain 'url()'
$markers = [];
$value = preg_replace_callback('/\burl\(.*\)/i', function($match) use (&$markers) {
$marker = sprintf('{marker:%s}', mt_rand());
$markers[$marker] = $match[0];
return $marker;
}, $value);
// now split the styles string on semicolons
$styles = ArrayHelper::filterEmptyStringsFromArray(preg_split('/\s*;\s*/', $value));
// and proceed with the array of styles
$normalized = [];
foreach ($styles as $style) {
[$n, $v] = array_pad(preg_split('/\s*:\s*/', $style, 2), 2, '');
$normalized[$n] = strtr($v, $markers);
}
return $normalized;
}
throw new InvalidArgumentException('Invalid style value');
}
/**
* Finds the first tag defined in some HTML that isn't a comment or DTD.
*
* @param string $html
* @param int $offset
* @return array{non-empty-string, int} The tag type and starting position
* @throws InvalidHtmlTagException
*/
private static function _findTag(string $html, int $offset = 0): array
{
// Find the first HTML tag that isn't a DTD or a comment
if (!preg_match('/<(\/?[\w\-]+)/', $html, $match, PREG_OFFSET_CAPTURE, $offset) || $match[1][0][0] === '/') {
throw new InvalidHtmlTagException(
"Could not find an HTML tag in string: $html",
isset($match[1][0]) ? strtolower($match[1][0]) : null,
null,
$match[0][1] ?? null
);
}
return [strtolower($match[1][0]), $match[0][1]];
}
/**
* Appends or prepends HTML to the beginning of a string.
*
* @param string $tag
* @param string $html
* @param string $position
* @param string|null $ifExists
* @return string
*/
private static function _addToTagInternal(string $tag, string $html, string $position, ?string $ifExists = null): string
{
$info = static::parseTag($tag);
// Make sure it’s not a void tag
if (!isset($info['htmlStart'])) {
throw new InvalidArgumentException("<{$info['type']}> can't have children.");
}
if ($ifExists) {
// See if we have a child of the same type
[$type] = self::_findTag($html);
$child = ArrayHelper::firstWhere($info['children'], 'type', $type, true);
if ($child) {
return match ($ifExists) {
'keep' => $tag,
'replace' => substr($tag, 0, $child['start']) .
$html .
substr($tag, $child['end']),
default => throw new InvalidArgumentException('Invalid $ifExists value: ' . $ifExists),
};
}
}
return substr($tag, 0, $info[$position]) .
$html .
substr($tag, $info[$position]);
}
private static function _sortedDataAttributes(): array
{
if (!isset(self::$_sortedDataAttributes)) {
self::$_sortedDataAttributes = array_merge(static::$dataAttributes);
usort(self::$_sortedDataAttributes, fn(string $a, string $b): int => strlen($b) - strlen($a));
}
return self::$_sortedDataAttributes;
}
/**
* Unwraps an IE conditional comment from the given HTML.
*
* @param string $content
* @return array[] An array containing the HTML content, and the condition (if there is one).
* @phpstan-return array{string,string|null}
* @see wrapIntoCondition()
* @since 4.0.0
*/
public static function unwrapCondition(string $content): array
{
if (preg_match('/^<!--\[if (.*?)]>(?:<!-->)?\\n(.*)\\n<!(?:--<!)?\[endif]-->$/s', $content, $match)) {
$condition = $match[1];
$content = $match[2];
} else {
$condition = null;
}
return [$content, $condition];
}
/**
* Unwraps a `<noscript>` tag from the given HTML.
*
* @param string $content
* @return array[] An array containing the HTML content, and whether a `<noscript>` tag was found.
* @phpstan-return array{string,bool}
* @since 4.0.0
*/
public static function unwrapNoscript(string $content): array
{
if (preg_match('/^<noscript>(.*)<\/noscript>$/s', $content, $match)) {
$noscript = true;
$content = $match[1];
} else {
$noscript = false;
}
return [$content, $noscript];
}
/**
* Normalizes an element ID into only alphanumeric characters, underscores, and hyphens, or generates one at random.
*
* @param string $id
* @return string
* @since 3.5.0
*/
public static function id(string $id = ''): string
{
// Ignore if it looks like a placeholder
// or starts with a placeholder (e.g. widgets > __NAMESPACE__-fieldId)
if (preg_match('/^__[A-Z_]+__/', $id)) {
return $id;
}
// remove any non-alphanumeric characters that are already preceded/followed by a hyphen
$id = preg_replace('/(?<=-)[^A-Za-z0-9_.-]+|[^A-Za-z0-9_.-]+(?=-)/', '', $id);
// convert any remaining consecutive non-alphanumeric characters to hyphens
$id = trim(preg_replace('/[^A-Za-z0-9_.-]+/', '-', $id), '-');
return $id ?: StringHelper::randomString(10);
}
/**
* Namespaces an input name.
*
* @param string $inputName The input name
* @param string|null $namespace The namespace
* @return string The namespaced input name
* @since 3.5.0
*/
public static function namespaceInputName(string $inputName, ?string $namespace): string
{
if ($namespace === null) {
return $inputName;
}
return preg_replace('/([^\'"\[\]]+)([^\'"]*)/', $namespace . '[$1]$2', $inputName);
}
/**
* Namespaces an ID.
*
* @param string $id The ID
* @param string|null $namespace The namespace
* @return string The namespaced ID
* @since 3.5.0
*/
public static function namespaceId(string $id, ?string $namespace): string
{
if ($namespace === null) {
return static::id($id);
}
return static::id("$namespace-$id");
}
/**
* Namespaces input names and other HTML attributes, as well as CSS selectors.
*
* This is a shortcut for calling [[namespaceInputs()]] and [[namespaceAttributes()]].
*
* @param string $html The HTML code
* @param string $namespace The namespace
* @param bool $withClasses Whether class names should be namespaced as well (affects both `class` attributes and class name CSS selectors)
* @return string The HTML with namespaced attributes
* @since 3.5.0
*/
public static function namespaceHtml(string $html, string $namespace, bool $withClasses = false): string
{
$markers = self::_escapeTextareas($html);
self::_namespaceInputs($html, $namespace);
self::_namespaceAttributes($html, $namespace, $withClasses);
return self::_restoreTextareas($html, $markers);
}
/**
* Renames HTML input names so they belong to a namespace.
*
* This method will go through the passed-in HTML code looking for `name` attributes, and namespace their values.
*
* For example, this:
*
* ```html
* <input type="text" name="title">
* <textarea name="fields[body]"></textarea>
* ```
*
* would become this, if it were namespaced with `foo`:
*
* ```html
* <input type="text" name="foo[title]">
* <textarea name="foo[fields][body]"></textarea>
* ```
*
* @param string $html The HTML code
* @param string $namespace The namespace
* @return string The HTML with namespaced input names
* @see namespaceHtml()
* @see namespaceAttributes()
* @since 3.5.0
*/
public static function namespaceInputs(string $html, string $namespace): string
{
$markers = self::_escapeTextareas($html);
self::_namespaceInputs($html, $namespace);
return self::_restoreTextareas($html, $markers);
}
/**
* @param string $html
* @param string $namespace
*/
private static function _namespaceInputs(string &$html, string $namespace): void
{
$html = preg_replace('/(?<![\w\-])(name=(\'|"))([^\'"\[\]]+)([^\'"]*)\2/i', '${1}' . $namespace . '[$3]$4$2', $html) ?? '';
}
/**
* Prepends a namespace to `id` attributes, and any of the following things that reference those IDs:
*
* - `for`, `list`, `href`, `aria-labelledby`, `aria-describedby`, `aria-controls`, `data-target`, `data-reverse-target`, and `data-target-prefix` attributes
* - ID selectors within `<style>` tags
*
* For example, this:
*
* ```html
* <style>#summary { font-size: larger }</style>
* <p id="summary">...</p>
* ```
*
* would become this, if it were namespaced with `foo`:
*
* ```html
* <style>#foo-summary { font-size: larger }</style>
* <p id="foo-summary">...</p>
* ```
*
* @param string $html The HTML code
* @param string $namespace The namespace
* @param bool $withClasses Whether class names should be namespaced as well (affects both `class` attributes and class name CSS selectors)
* @return string The HTML with namespaced attributes
* @see namespaceHtml()
* @see namespaceInputs()
* @since 3.5.0
*/
public static function namespaceAttributes(string $html, string $namespace, bool $withClasses = false): string
{
$markers = self::_escapeTextareas($html);
self::_namespaceAttributes($html, $namespace, $withClasses);
return self::_restoreTextareas($html, $markers);
}
/**
* @param string $html
* @param string $namespace
* @param bool $withClasses
*/
private static function _namespaceAttributes(string &$html, string $namespace, bool $withClasses): void
{
// normalize the namespace
$namespace = static::id($namespace);
// Namespace & capture the ID attributes
$ids = [];
$html = preg_replace_callback('/(?<=\sid=)(\'|")([^\'"\s]*)\1/i', function($match) use ($namespace, &$ids): string {
$ids[] = $match[2];
return $match[1] . $namespace . '-' . $match[2] . $match[1];
}, $html) ?? '';
$ids = array_flip($ids);
// normal HTML attributes
$html = preg_replace_callback(
"/(?<=\\s)((for|list|xlink:href|href|aria\\-labelledby|aria\\-describedby|aria\\-controls|aria\\-activedescendant|aria\\-flowto|aria\\-owns|data\\-target|data\\-reverse\\-target|data\\-target\\-prefix)=('|\"))([^'\"]+)\\3/i",
function(array $match) use ($namespace, $ids): string {
$matchIds = preg_split('/([,\s+]+)/', $match[4], flags: PREG_SPLIT_DELIM_CAPTURE);
$namespacedIds = '';
foreach ($matchIds as $i => $id) {
if (
$i % 2 === 0 && // not a delimiter
$id[0] !== '.' // not a class name
) {
$isHash = $id[0] === '#';
if ($isHash) {
$id = substr($id, 1);
}
if (
isset($ids[$id]) ||
$match[2] === 'data-target-prefix' ||
($isHash && $match[2] === 'href')
) {
$id = sprintf('%s-%s', $namespace, $id);
}
if ($isHash) {
$id = "#$id";
}
}
$namespacedIds .= $id;
}
return sprintf('%s%s%s', $match[1], $namespacedIds, $match[3]);
}, $html) ?? '';
// ID references in url() calls
$html = preg_replace_callback(
"/(?<=url\\(#)[^'\"\s\)]*(?=\\))/i",
function(array $match) use ($namespace, $ids): string {
if (isset($ids[$match[0]])) {
return $namespace . '-' . $match[0];
}
return $match[0];
}, $html) ?? '';
// class attributes
if ($withClasses) {
$html = preg_replace_callback('/(?<![\w\-])\bclass=(\'|")([^\'"]+)\\1/i', function($match) use ($namespace) {
$newClasses = [];
foreach (preg_split('/\s+/', $match[2]) as $class) {
$newClasses[] = "$namespace-$class";
}
return 'class=' . $match[1] . implode(' ', $newClasses) . $match[1];
}, $html) ?? '';
}
// CSS selectors
$html = preg_replace_callback(
'/(<style\b[^>]*>)(.*?)(<\/style>)/is',
function(array $match) use ($namespace, $withClasses, $ids) {
$html = preg_replace_callback(
"/(?<![\w'\"])#([^'\"\s]*)(?=[,\\s\\{])/",
function(array $match) use ($namespace, $ids): string {
if (isset($ids[$match[1]])) {
return '#' . $namespace . '-' . $match[1];
}
return $match[0];
}, $match[2]);
if ($withClasses) {
$html = preg_replace("/(?<![\\w'\"])\\.([\\w\\-]+)(?=[,:\\s{])/", ".$namespace-$1", $match[2]);
}
return $match[1] . $html . $match[3];
}, $html) ?? '';
}
/**
* Replaces textareas with markers
*
* @param string $html
* @return array<string, string>
*/
private static function _escapeTextareas(string &$html): array
{
$markers = [];
$offset = 0;
$r = '';
while (($pos = stripos($html, '<textarea', $offset)) !== false) {
$gtPos = strpos($html, '>', $pos + 9);
if ($gtPos === false) {
break;
}
$innerHtmlPos = $gtPos + 1;
$closePos = stripos($html, '</textarea>', $innerHtmlPos);
if ($closePos === false) {
break;
}
$outerPos = $closePos + 11;
$innerHtml = $closePos !== $innerHtmlPos ? substr($html, $innerHtmlPos, $closePos - $innerHtmlPos) : null;
if ($innerHtml !== null && str_contains($innerHtml, '<')) {
$marker = sprintf('{marker:%s}', mt_rand());
$r .= substr($html, $offset, $innerHtmlPos - $offset) . $marker . substr($html, $closePos, 11);
$markers[$marker] = $innerHtml;
} else {
$r .= substr($html, $offset, $outerPos - $offset);
}