forked from MyIntervals/emogrifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Emogrifier.php
1987 lines (1797 loc) · 64 KB
/
Emogrifier.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
namespace Pelago;
/**
* This class provides functions for converting CSS styles into inline style attributes in your HTML code.
*
* For more information, please see the README.md file.
*
* @version 2.0.0
*
* @author Cameron Brooks
* @author Jaime Prado
* @author Oliver Klee <[email protected]>
* @author Roman Ožana <[email protected]>
* @author Sander Kruger <[email protected]>
* @author Zoli Szabó <[email protected]>
*/
class Emogrifier
{
/**
* @var int
*/
const CACHE_KEY_CSS = 0;
/**
* @var int
*/
const CACHE_KEY_SELECTOR = 1;
/**
* @var int
*/
const CACHE_KEY_XPATH = 2;
/**
* @var int
*/
const CACHE_KEY_CSS_DECLARATIONS_BLOCK = 3;
/**
* @var int
*/
const CACHE_KEY_COMBINED_STYLES = 4;
/**
* for calculating nth-of-type and nth-child selectors
*
* @var int
*/
const INDEX = 0;
/**
* for calculating nth-of-type and nth-child selectors
*
* @var int
*/
const MULTIPLIER = 1;
/**
* @var string
*/
const ID_ATTRIBUTE_MATCHER = '/(\\w+)?\\#([\\w\\-]+)/';
/**
* @var string
*/
const CLASS_ATTRIBUTE_MATCHER = '/(\\w+|[\\*\\]])?((\\.[\\w\\-]+)+)/';
/**
* Regular expression component matching a static pseudo class in a selector, without the preceding ":",
* for which the applicable elements can be determined (by converting the selector to an XPath expression).
* (Contains alternation without a group and is intended to be placed within a capturing, non-capturing or lookahead
* group, as appropriate for the usage context.)
*
* @var string
*/
const PSEUDO_CLASS_MATCHER = '\\S+\\-(?:child|type\\()|not\\([[:ascii:]]*\\)';
/**
* @var string
*/
const CONTENT_TYPE_META_TAG = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
/**
* @var string
*/
const DEFAULT_DOCUMENT_TYPE = '<!DOCTYPE html>';
/**
* @var string
*/
private $html = '';
/**
* @var string
*/
private $css = '';
/**
* @var bool[]
*/
private $excludedSelectors = [];
/**
* @var string[]
*/
private $unprocessableHtmlTags = ['wbr'];
/**
* @var bool[]
*/
private $allowedMediaTypes = ['all' => true, 'screen' => true, 'print' => true];
/**
* @var mixed[]
*/
private $caches = [
self::CACHE_KEY_CSS => [],
self::CACHE_KEY_SELECTOR => [],
self::CACHE_KEY_XPATH => [],
self::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [],
self::CACHE_KEY_COMBINED_STYLES => [],
];
/**
* the visited nodes with the XPath paths as array keys
*
* @var \DOMElement[]
*/
private $visitedNodes = [];
/**
* the styles to apply to the nodes with the XPath paths as array keys for the outer array
* and the attribute names/values as key/value pairs for the inner array
*
* @var string[][]
*/
private $styleAttributesForNodes = [];
/**
* Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved.
* If set to false, the value of the style attributes will be discarded.
*
* @var bool
*/
private $isInlineStyleAttributesParsingEnabled = true;
/**
* Determines whether the <style> blocks in the HTML passed to this class should be parsed.
*
* If set to true, the <style> blocks will be removed from the HTML and their contents will be applied to the HTML
* via inline styles.
*
* If set to false, the <style> blocks will be left as they are in the HTML.
*
* @var bool
*/
private $isStyleBlocksParsingEnabled = true;
/**
* Determines whether elements with the `display: none` property are
* removed from the DOM.
*
* @var bool
*/
private $shouldRemoveInvisibleNodes = true;
/**
* For calculating selector precedence order.
* Keys are a regular expression part to match before a CSS name.
* Values are a multiplier factor per match to weight specificity.
*
* @var int[]
*/
private $selectorPrecedenceMatchers = [
// IDs: worth 10000
'\\#' => 10000,
// classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100
'(?:\\.|\\[|(?<!:):(?!not\\())' => 100,
// elements (not attribute values or `:not`), pseudo-elements: worth 1
'(?:(?<![="\':\\w-])|::)' => 1
];
/**
* @var string[]
*/
private $xPathRules = [
// attribute presence
'/^\\[(\\w+|\\w+\\=[\'"]?\\w+[\'"]?)\\]/' => '*[@\\1]',
// type and attribute exact value
'/(\\w)\\[(\\w+)\\=[\'"]?([\\w\\s]+)[\'"]?\\]/' => '\\1[@\\2="\\3"]',
// type and attribute value with ~ (one word within a whitespace-separated list of words)
'/([\\w\\*]+)\\[(\\w+)[\\s]*\\~\\=[\\s]*[\'"]?([\\w-_\\/]+)[\'"]?\\]/'
=> '\\1[contains(concat(" ", @\\2, " "), concat(" ", "\\3", " "))]',
// type and attribute value with | (either exact value match or prefix followed by a hyphen)
'/([\\w\\*]+)\\[(\\w+)[\\s]*\\|\\=[\\s]*[\'"]?([\\w-_\\s\\/]+)[\'"]?\\]/'
=> '\\1[@\\2="\\3" or starts-with(@\\2, concat("\\3", "-"))]',
// type and attribute value with ^ (prefix match)
'/([\\w\\*]+)\\[(\\w+)[\\s]*\\^\\=[\\s]*[\'"]?([\\w-_\\/]+)[\'"]?\\]/' => '\\1[starts-with(@\\2, "\\3")]',
// type and attribute value with * (substring match)
'/([\\w\\*]+)\\[(\\w+)[\\s]*\\*\\=[\\s]*[\'"]?([\\w-_\\s\\/:;]+)[\'"]?\\]/' => '\\1[contains(@\\2, "\\3")]',
// adjacent sibling
'/\\s*\\+\\s*/' => '/following-sibling::*[1]/self::',
// child
'/\\s*>\\s*/' => '/',
// descendant (don't match spaces within already translated XPath predicates)
'/\\s+(?![^\\[\\]]*+\\])/' => '//',
// type and :first-child
'/([^\\/]+):first-child/i' => '*[1]/self::\\1',
// type and :last-child
'/([^\\/]+):last-child/i' => '*[last()]/self::\\1',
// The following matcher will break things if it is placed before the adjacent matcher.
// So one of the matchers matches either too much or not enough.
// type and attribute value with $ (suffix match)
'/([\\w\\*]+)\\[(\\w+)[\\s]*\\$\\=[\\s]*[\'"]?([\\w-_\\s\\/]+)[\'"]?\\]/'
=> '\\1[substring(@\\2, string-length(@\\2) - string-length("\\3") + 1) = "\\3"]',
];
/**
* Determines whether CSS styles that have an equivalent HTML attribute
* should be mapped and attached to those elements.
*
* @var bool
*/
private $shouldMapCssToHtml = false;
/**
* This multi-level array contains simple mappings of CSS properties to
* HTML attributes. If a mapping only applies to certain HTML nodes or
* only for certain values, the mapping is an object with a whitelist
* of nodes and values.
*
* @var mixed[][]
*/
private $cssToHtmlMap = [
'background-color' => [
'attribute' => 'bgcolor',
],
'text-align' => [
'attribute' => 'align',
'nodes' => ['p', 'div', 'td'],
'values' => ['left', 'right', 'center', 'justify'],
],
'float' => [
'attribute' => 'align',
'nodes' => ['table', 'img'],
'values' => ['left', 'right'],
],
'border-spacing' => [
'attribute' => 'cellspacing',
'nodes' => ['table'],
],
];
/**
* Emogrifier will throw Exceptions when it encounters an error instead of silently ignoring them.
*
* @var bool
*/
private $debug = false;
/**
* The constructor.
*
* @param string $html the HTML to emogrify, must be UTF-8-encoded
* @param string $css the CSS to merge, must be UTF-8-encoded
*/
public function __construct($html = '', $css = '')
{
$this->setHtml($html);
$this->setCss($css);
}
/**
* The destructor.
*/
public function __destruct()
{
$this->purgeVisitedNodes();
}
/**
* Sets the HTML to emogrify.
*
* @param string $html the HTML to emogrify, must be UTF-8-encoded
*
* @return void
*/
public function setHtml($html)
{
$this->html = $html;
}
/**
* Sets the CSS to merge with the HTML.
*
* @param string $css the CSS to merge, must be UTF-8-encoded
*
* @return void
*/
public function setCss($css)
{
$this->css = $css;
}
/**
* Applies $this->css to $this->html and returns the HTML with the CSS
* applied.
*
* This method places the CSS inline.
*
* @param bool $prevent_transformations Set true to prevent urls encoding and other HTML transformations
*
* @return string
*
* @throws \BadMethodCallException
*/
public function emogrify($prevent_transformations = false)
{
$doc = $this->createAndProcessXmlDocument();
if($prevent_transformations){
return $doc->saveXML($doc->documentElement);
} else {
return $doc->saveHTML();
}
}
/**
* Applies $this->css to $this->html and returns only the HTML content
* within the <body> tag.
*
* This method places the CSS inline.
*
* @return string
*
* @throws \BadMethodCallException
*/
public function emogrifyBodyContent()
{
$xmlDocument = $this->createAndProcessXmlDocument();
$bodyNodeHtml = $xmlDocument->saveHTML($this->getBodyElement($xmlDocument));
return str_replace(['<body>', '</body>'], '', $bodyNodeHtml);
}
/**
* Creates an XML document from $this->html and emogrifies ist.
*
* @return \DOMDocument
*
* @throws \BadMethodCallException
*/
private function createAndProcessXmlDocument()
{
if ($this->html === '') {
throw new \BadMethodCallException('Please set some HTML first.', 1390393096);
}
$xmlDocument = $this->createRawXmlDocument();
$this->ensureExistenceOfBodyElement($xmlDocument);
$this->process($xmlDocument);
return $xmlDocument;
}
/**
* Applies $this->css to $xmlDocument.
*
* This method places the CSS inline.
*
* @param \DOMDocument $xmlDocument
*
* @return void
*
* @throws \InvalidArgumentException
*/
protected function process(\DOMDocument $xmlDocument)
{
$xPath = new \DOMXPath($xmlDocument);
$this->clearAllCaches();
$this->purgeVisitedNodes();
set_error_handler([$this, 'handleXpathQueryWarnings'], E_WARNING);
$this->normalizeStyleAttributesOfAllNodes($xPath);
// grab any existing style blocks from the html and append them to the existing CSS
// (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
$allCss = $this->css;
if ($this->isStyleBlocksParsingEnabled) {
$allCss .= $this->getCssFromAllStyleNodes($xPath);
}
$excludedNodes = $this->getNodesToExclude($xPath);
$cssRules = $this->parseCssRules($allCss);
foreach ($cssRules['inlineable'] as $cssRule) {
// There's no real way to test "PHP Warning" output generated by the following XPath query unless PHPUnit
// converts it to an exception. Unfortunately, this would only apply to tests and not work for production
// executions, which can still flood logs/output unnecessarily. Instead, Emogrifier's error handler should
// always throw an exception and it must be caught here and only rethrown if in debug mode.
try {
// \DOMXPath::query will always return a DOMNodeList or throw an exception when errors are caught.
$nodesMatchingCssSelectors = $xPath->query($this->translateCssToXpath($cssRule['selector']));
} catch (\InvalidArgumentException $e) {
if ($this->debug) {
throw $e;
}
continue;
}
/** @var \DOMElement $node */
foreach ($nodesMatchingCssSelectors as $node) {
if (in_array($node, $excludedNodes, true)) {
continue;
}
$this->copyInlineableCssToStyleAttribute($node, $cssRule);
}
}
if ($this->isInlineStyleAttributesParsingEnabled) {
$this->fillStyleAttributesWithMergedStyles();
}
$this->postProcess($xPath);
$this->removeImportantAnnotationFromAllInlineStyles($xPath);
$this->copyUninlineableCssToStyleNode($xmlDocument, $xPath, $cssRules['uninlineable']);
restore_error_handler();
}
/**
* Applies some optional post-processing to the HTML in the XML document.
*
* @param \DOMXPath $xPath
*
* @return void
*/
private function postProcess(\DOMXPath $xPath)
{
if ($this->shouldMapCssToHtml) {
$this->mapAllInlineStylesToHtmlAttributes($xPath);
}
if ($this->shouldRemoveInvisibleNodes) {
$this->removeInvisibleNodes($xPath);
}
}
/**
* Searches for all nodes with a style attribute, transforms the CSS found
* to HTML attributes and adds those attributes to each node.
*
* @param \DOMXPath $xPath
*
* @return void
*/
private function mapAllInlineStylesToHtmlAttributes(\DOMXPath $xPath)
{
/** @var \DOMElement $node */
foreach ($this->getAllNodesWithStyleAttribute($xPath) as $node) {
$inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
$this->mapCssToHtmlAttributes($inlineStyleDeclarations, $node);
}
}
/**
* Searches for all nodes with a style attribute and removes the "!important" annotations out of
* the inline style declarations, eventually by rearranging declarations.
*
* @param \DOMXPath $xPath
*
* @return void
*/
private function removeImportantAnnotationFromAllInlineStyles(\DOMXPath $xPath)
{
foreach ($this->getAllNodesWithStyleAttribute($xPath) as $node) {
$this->removeImportantAnnotationFromNodeInlineStyle($node);
}
}
/**
* Removes the "!important" annotations out of the inline style declarations,
* eventually by rearranging declarations.
* Rearranging needed when !important shorthand properties are followed by some of their
* not !important expanded-version properties.
* For example "font: 12px serif !important; font-size: 13px;" must be reordered
* to "font-size: 13px; font: 12px serif;" in order to remain correct.
*
* @param \DOMElement $node
*
* @return void
*/
private function removeImportantAnnotationFromNodeInlineStyle(\DOMElement $node)
{
$inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
$regularStyleDeclarations = [];
$importantStyleDeclarations = [];
foreach ($inlineStyleDeclarations as $property => $value) {
if ($this->attributeValueIsImportant($value)) {
$importantStyleDeclarations[$property] = trim(str_replace('!important', '', $value));
} else {
$regularStyleDeclarations[$property] = $value;
}
}
$inlineStyleDeclarationsInNewOrder = array_merge(
$regularStyleDeclarations,
$importantStyleDeclarations
);
$node->setAttribute(
'style',
$this->generateStyleStringFromSingleDeclarationsArray($inlineStyleDeclarationsInNewOrder)
);
}
/**
* Returns a list with all DOM nodes that have a style attribute.
*
* @param \DOMXPath $xPath
*
* @return \DOMNodeList
*/
private function getAllNodesWithStyleAttribute(\DOMXPath $xPath)
{
return $xPath->query('//*[@style]');
}
/**
* Applies $styles to $node.
*
* This method maps CSS styles to HTML attributes and adds those to the
* node.
*
* @param string[] $styles the new CSS styles taken from the global styles to be applied to this node
* @param \DOMElement $node node to apply styles to
*
* @return void
*/
private function mapCssToHtmlAttributes(array $styles, \DOMElement $node)
{
foreach ($styles as $property => $value) {
// Strip !important indicator
$value = trim(str_replace('!important', '', $value));
$this->mapCssToHtmlAttribute($property, $value, $node);
}
}
/**
* Tries to apply the CSS style to $node as an attribute.
*
* This method maps a CSS rule to HTML attributes and adds those to the node.
*
* @param string $property the name of the CSS property to map
* @param string $value the value of the style rule to map
* @param \DOMElement $node node to apply styles to
*
* @return void
*/
private function mapCssToHtmlAttribute($property, $value, \DOMElement $node)
{
if (!$this->mapSimpleCssProperty($property, $value, $node)) {
$this->mapComplexCssProperty($property, $value, $node);
}
}
/**
* Looks up the CSS property in the mapping table and maps it if it matches the conditions.
*
* @param string $property the name of the CSS property to map
* @param string $value the value of the style rule to map
* @param \DOMElement $node node to apply styles to
*
* @return bool true if the property can be mapped using the simple mapping table
*/
private function mapSimpleCssProperty($property, $value, \DOMElement $node)
{
if (!isset($this->cssToHtmlMap[$property])) {
return false;
}
$mapping = $this->cssToHtmlMap[$property];
$nodesMatch = !isset($mapping['nodes']) || in_array($node->nodeName, $mapping['nodes'], true);
$valuesMatch = !isset($mapping['values']) || in_array($value, $mapping['values'], true);
if (!$nodesMatch || !$valuesMatch) {
return false;
}
$node->setAttribute($mapping['attribute'], $value);
return true;
}
/**
* Maps CSS properties that need special transformation to an HTML attribute.
*
* @param string $property the name of the CSS property to map
* @param string $value the value of the style rule to map
* @param \DOMElement $node node to apply styles to
*
* @return void
*/
private function mapComplexCssProperty($property, $value, \DOMElement $node)
{
switch ($property) {
case 'background':
$this->mapBackgroundProperty($node, $value);
break;
case 'width':
// intentional fall-through
case 'height':
$this->mapWidthOrHeightProperty($node, $value, $property);
break;
case 'margin':
$this->mapMarginProperty($node, $value);
break;
case 'border':
$this->mapBorderProperty($node, $value);
break;
default:
}
}
/**
* Maps the "background" CSS property to visual HTML attributes.
*
* @param \DOMElement $node node to apply styles to
* @param string $value the value of the style rule to map
*
* @return void
*/
private function mapBackgroundProperty(\DOMElement $node, $value)
{
// parse out the color, if any
$styles = explode(' ', $value);
$first = $styles[0];
if (!is_numeric($first[0]) && strpos($first, 'url') !== 0) {
// as this is not a position or image, assume it's a color
$node->setAttribute('bgcolor', $first);
}
}
/**
* Maps the "width" or "height" CSS properties to visual HTML attributes.
*
* @param \DOMElement $node node to apply styles to
* @param string $value the value of the style rule to map
* @param string $property the name of the CSS property to map
*
* @return void
*/
private function mapWidthOrHeightProperty(\DOMElement $node, $value, $property)
{
// only parse values in px and %, but not values like "auto"
if (preg_match('/^\d+(px|%)$/', $value)) {
// Remove 'px'. This regex only conserves numbers and %.
$number = preg_replace('/[^0-9.%]/', '', $value);
$node->setAttribute($property, $number);
}
}
/**
* Maps the "margin" CSS property to visual HTML attributes.
*
* @param \DOMElement $node node to apply styles to
* @param string $value the value of the style rule to map
*
* @return void
*/
private function mapMarginProperty(\DOMElement $node, $value)
{
if (!$this->isTableOrImageNode($node)) {
return;
}
$margins = $this->parseCssShorthandValue($value);
if ($margins['left'] === 'auto' && $margins['right'] === 'auto') {
$node->setAttribute('align', 'center');
}
}
/**
* Maps the "border" CSS property to visual HTML attributes.
*
* @param \DOMElement $node node to apply styles to
* @param string $value the value of the style rule to map
*
* @return void
*/
private function mapBorderProperty(\DOMElement $node, $value)
{
if (!$this->isTableOrImageNode($node)) {
return;
}
if ($value === 'none' || $value === '0') {
$node->setAttribute('border', '0');
}
}
/**
* Checks whether $node is a table or img element.
*
* @param \DOMElement $node
*
* @return bool
*/
private function isTableOrImageNode(\DOMElement $node)
{
return $node->nodeName === 'table' || $node->nodeName === 'img';
}
/**
* Parses a shorthand CSS value and splits it into individual values
*
* @param string $value a string of CSS value with 1, 2, 3 or 4 sizes
* For example: padding: 0 auto;
* '0 auto' is split into top: 0, left: auto, bottom: 0,
* right: auto.
*
* @return string[] an array of values for top, right, bottom and left (using these as associative array keys)
*/
private function parseCssShorthandValue($value)
{
$values = preg_split('/\\s+/', $value);
$css = [];
$css['top'] = $values[0];
$css['right'] = (count($values) > 1) ? $values[1] : $css['top'];
$css['bottom'] = (count($values) > 2) ? $values[2] : $css['top'];
$css['left'] = (count($values) > 3) ? $values[3] : $css['right'];
return $css;
}
/**
* Extracts and parses the individual rules from a CSS string.
*
* @param string $css a string of raw CSS code
*
* @return string[][][] A 2-entry array with the key "inlineable" containing rules which can be inlined as `style`
* attributes and the key "uninlineable" containing rules which cannot. Each value is an array of string
* sub-arrays with the keys
* "media" (the media query string, e.g. "@media screen and (max-width: 480px)",
* or an empty string if not from a `@media` rule),
* "selector" (the CSS selector(s), e.g., "*" or "h1"),
* "declarationsBLock" (the semicolon-separated CSS declarations for that selector(s),
* e.g., "color: red; height: 4px;"),
* and "line" (the line number e.g. 42)
*/
private function parseCssRules($css)
{
$cssKey = md5($css);
if (!isset($this->caches[static::CACHE_KEY_CSS][$cssKey])) {
$matches = $this->getCssRuleMatches($css);
$cssRules = [
'inlineable' => [],
'uninlineable' => [],
];
/** @var string[][] $matches */
/** @var string[] $cssRule */
foreach ($matches as $key => $cssRule) {
$cssDeclaration = trim($cssRule['declarations']);
if ($cssDeclaration === '') {
continue;
}
$selectors = explode(',', $cssRule['selectors']);
foreach ($selectors as $selector) {
// don't process pseudo-elements and behavioral (dynamic) pseudo-classes;
// only allow structural pseudo-classes
$hasPseudoElement = strpos($selector, '::') !== false;
$hasUnsupportedPseudoClass = (bool)preg_match(
'/:(?!' . static::PSEUDO_CLASS_MATCHER . ')[\\w-]/i',
$selector
);
$hasUnmatchablePseudo = $hasPseudoElement || $hasUnsupportedPseudoClass;
$parsedCssRule = [
'media' => $cssRule['media'],
'selector' => trim($selector),
'hasUnmatchablePseudo' => $hasUnmatchablePseudo,
'declarationsBlock' => $cssDeclaration,
// keep track of where it appears in the file, since order is important
'line' => $key,
];
$ruleType = ($cssRule['media'] === '' && !$hasUnmatchablePseudo) ? 'inlineable' : 'uninlineable';
$cssRules[$ruleType][] = $parsedCssRule;
}
}
usort($cssRules['inlineable'], [$this, 'sortBySelectorPrecedence']);
$this->caches[static::CACHE_KEY_CSS][$cssKey] = $cssRules;
}
return $this->caches[static::CACHE_KEY_CSS][$cssKey];
}
/**
* Parses a string of CSS into the media query, selectors and declarations for each ruleset in order.
*
* @param string $css
*
* @return string[][] Array of string sub-arrays with the keys
* "media" (the media query string, e.g. "@media screen and (max-width: 480px)",
* or an empty string if not from an `@media` rule),
* "selectors" (the CSS selector(s), e.g., "*" or "h1, h2"),
* "declarations" (the semicolon-separated CSS declarations for that/those selector(s),
* e.g., "color: red; height: 4px;"),
*/
private function getCssRuleMatches($css)
{
$ruleMatches = [];
$splitCss = $this->splitCssAndMediaQuery($css);
foreach ($splitCss as $cssPart) {
// process each part for selectors and definitions
preg_match_all('/(?:^|[\\s^{}]*)([^{]+){([^}]*)}/mi', $cssPart['css'], $matches, PREG_SET_ORDER);
foreach ($matches as $cssRule) {
$ruleMatches[] = [
'media' => $cssPart['media'],
'selectors' => $cssRule[1],
'declarations' => $cssRule[2],
];
}
}
return $ruleMatches;
}
/**
* Disables the parsing of inline styles.
*
* @return void
*/
public function disableInlineStyleAttributesParsing()
{
$this->isInlineStyleAttributesParsingEnabled = false;
}
/**
* Disables the parsing of <style> blocks.
*
* @return void
*/
public function disableStyleBlocksParsing()
{
$this->isStyleBlocksParsingEnabled = false;
}
/**
* Disables the removal of elements with `display: none` properties.
*
* @deprecated will be removed in Emogrifier 3.0
*
* @return void
*/
public function disableInvisibleNodeRemoval()
{
$this->shouldRemoveInvisibleNodes = false;
}
/**
* Enables the attachment/override of HTML attributes for which a
* corresponding CSS property has been set.
*
* @deprecated will be removed in Emogrifier 3.0, use the CssToAttributeConverter instead
*
* @return void
*/
public function enableCssToHtmlMapping()
{
$this->shouldMapCssToHtml = true;
}
/**
* Clears all caches.
*
* @return void
*/
private function clearAllCaches()
{
$this->caches = [
static::CACHE_KEY_CSS => [],
static::CACHE_KEY_SELECTOR => [],
static::CACHE_KEY_XPATH => [],
static::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [],
static::CACHE_KEY_COMBINED_STYLES => [],
];
}
/**
* Purges the visited nodes.
*
* @return void
*/
private function purgeVisitedNodes()
{
$this->visitedNodes = [];
$this->styleAttributesForNodes = [];
}
/**
* Marks a tag for removal.
*
* There are some HTML tags that DOMDocument cannot process, and it will throw an error if it encounters them.
* In particular, DOMDocument will complain if you try to use HTML5 tags in an XHTML document.
*
* Note: The tags will not be removed if they have any content.
*
* @param string $tagName the tag name, e.g., "p"
*
* @return void
*/
public function addUnprocessableHtmlTag($tagName)
{
$this->unprocessableHtmlTags[] = $tagName;
}
/**
* Drops a tag from the removal list.
*
* @param string $tagName the tag name, e.g., "p"
*
* @return void
*/
public function removeUnprocessableHtmlTag($tagName)
{
$key = array_search($tagName, $this->unprocessableHtmlTags, true);
if ($key !== false) {
unset($this->unprocessableHtmlTags[$key]);
}
}
/**
* Marks a media query type to keep.
*
* @param string $mediaName the media type name, e.g., "braille"
*
* @return void
*/
public function addAllowedMediaType($mediaName)
{
$this->allowedMediaTypes[$mediaName] = true;
}
/**
* Drops a media query type from the allowed list.
*
* @param string $mediaName the tag name, e.g., "braille"
*
* @return void
*/
public function removeAllowedMediaType($mediaName)
{
if (isset($this->allowedMediaTypes[$mediaName])) {
unset($this->allowedMediaTypes[$mediaName]);
}
}
/**
* Adds a selector to exclude nodes from emogrification.
*
* Any nodes that match the selector will not have their style altered.
*
* @param string $selector the selector to exclude, e.g., ".editor"
*
* @return void
*/
public function addExcludedSelector($selector)
{
$this->excludedSelectors[$selector] = true;
}
/**
* No longer excludes the nodes matching this selector from emogrification.
*
* @param string $selector the selector to no longer exclude, e.g., ".editor"
*
* @return void
*/
public function removeExcludedSelector($selector)
{
if (isset($this->excludedSelectors[$selector])) {
unset($this->excludedSelectors[$selector]);
}
}
/**
* This removes styles from your email that contain display:none.
* We need to look for display:none, but we need to do a case-insensitive search. Since DOMDocument only
* supports XPath 1.0, lower-case() isn't available to us. We've thus far only set attributes to lowercase,
* not attribute values. Consequently, we need to translate() the letters that would be in 'NONE' ("NOE")
* to lowercase.
*
* @param \DOMXPath $xPath