-
Notifications
You must be signed in to change notification settings - Fork 0
/
CssToInlineStyles.php
698 lines (570 loc) · 20.4 KB
/
CssToInlineStyles.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
<?php
namespace TijsVerkoyen\CssToInlineStyles;
/**
* CSS to Inline Styles class
*
* @author Tijs Verkoyen <[email protected]>
* @version 1.1.0
* @copyright Copyright (c), Tijs Verkoyen. All rights reserved.
* @license BSD License
*/
class CssToInlineStyles
{
/**
* The CSS to use
*
* @var string
*/
private $css;
/**
* The processed CSS rules
*
* @var array
*/
private $cssRules;
/**
* Should the generated HTML be cleaned
*
* @var bool
*/
private $cleanup = false;
/**
* The encoding to use.
*
* @var string
*/
private $encoding = 'UTF-8';
/**
* The HTML to process
*
* @var string
*/
private $html;
/**
* Use inline-styles block as CSS
*
* @var bool
*/
private $useInlineStylesBlock = false;
/*
* Strip original style tags
*
* @var bool
*/
private $stripOriginalStyleTags = false;
/**
* Creates an instance, you could set the HTML and CSS here, or load it
* later.
*
* @return void
* @param string[optional] $html The HTML to process.
* @param string[optional] $css The CSS to use.
*/
public function __construct($html = null, $css = null)
{
if($html !== null) $this->setHTML($html);
if($css !== null) $this->setCSS($css);
}
/**
* Convert a CSS-selector into an xPath-query
*
* @return string
* @param string $selector The CSS-selector.
*/
private function buildXPathQuery($selector)
{
// redefine
$selector = (string) $selector;
// the CSS selector
$cssSelector = array(
// E F, Matches any F element that is a descendant of an E element
'/(\w)\s+(\w)/',
// E > F, Matches any F element that is a child of an element E
'/(\w)\s*>\s*(\w)/',
// E:first-child, Matches element E when E is the first child of its parent
'/(\w):first-child/',
// E + F, Matches any F element immediately preceded by an element
'/(\w)\s*\+\s*(\w)/',
// E[foo], Matches any E element with the "foo" attribute set (whatever the value)
'/(\w)\[([\w\-]+)]/',
// E[foo="warning"], Matches any E element whose "foo" attribute value is exactly equal to "warning"
'/(\w)\[([\w\-]+)\=\"(.*)\"]/',
// div.warning, HTML only. The same as DIV[class~="warning"]
'/(\w+|\*)+\.([\w\-]+)+/',
// .warning, HTML only. The same as *[class~="warning"]
'/\.([\w\-]+)/',
// E#myid, Matches any E element with id-attribute equal to "myid"
'/(\w+)+\#([\w\-]+)/',
// #myid, Matches any element with id-attribute equal to "myid"
'/\#([\w\-]+)/'
);
// the xPath-equivalent
$xPathQuery = array(
// E F, Matches any F element that is a descendant of an E element
'\1//\2',
// E > F, Matches any F element that is a child of an element E
'\1/\2',
// E:first-child, Matches element E when E is the first child of its parent
'*[1]/self::\1',
// E + F, Matches any F element immediately preceded by an element
'\1/following-sibling::*[1]/self::\2',
// E[foo], Matches any E element with the "foo" attribute set (whatever the value)
'\1 [ @\2 ]',
// E[foo="warning"], Matches any E element whose "foo" attribute value is exactly equal to "warning"
'\1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]',
// div.warning, HTML only. The same as DIV[class~="warning"]
'\1[ contains( concat( " ", @class, " " ), concat( " ", "\2", " " ) ) ]',
// .warning, HTML only. The same as *[class~="warning"]
'*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]',
// E#myid, Matches any E element with id-attribute equal to "myid"
'\1[ @id = "\2" ]',
// #myid, Matches any element with id-attribute equal to "myid"
'*[ @id = "\1" ]'
);
// return
$xPath = (string) '//' . preg_replace($cssSelector, $xPathQuery, $selector);
return str_replace('] *', ']//*', $xPath);
}
/**
* Calculate the specifity for the CSS-selector
*
* @return int
* @param string $selector The selector to calculate the specifity for.
*/
private function calculateCSSSpecifity($selector)
{
// cleanup selector
$selector = str_replace(array('>', '+'), array(' > ', ' + '), $selector);
// init var
$specifity = 0;
// split the selector into chunks based on spaces
$chunks = explode(' ', $selector);
// loop chunks
foreach ($chunks as $chunk) {
// an ID is important, so give it a high specifity
if(strstr($chunk, '#') !== false) $specifity += 100;
// classes are more important than a tag, but less important then an ID
elseif(strstr($chunk, '.')) $specifity += 10;
// anything else isn't that important
else $specifity += 1;
}
// return
return $specifity;
}
/**
* Cleanup the generated HTML
*
* @return string
* @param string $html The HTML to cleanup.
*/
private function cleanupHTML($html)
{
// remove classes
$html = preg_replace('/(\s)+class="(.*)"(\s)+/U', ' ', $html);
// remove IDs
$html = preg_replace('/(\s)+id="(.*)"(\s)+/U', ' ', $html);
// return
return $html;
}
/**
* Converts the loaded HTML into an HTML-string with inline styles based on the loaded CSS
*
* @return string
* @param bool[optional] $outputXHTML Should we output valid XHTML?
*/
public function convert($outputXHTML = false)
{
// redefine
$outputXHTML = (bool) $outputXHTML;
// validate
if($this->html == null) throw new Exception('No HTML provided.');
// should we use inline style-block
if ($this->useInlineStylesBlock) {
// init var
$matches = array();
// match the style blocks
preg_match_all('|<style(.*)>(.*)</style>|isU', $this->html, $matches);
// any style-blocks found?
if (!empty($matches[2])) {
// add
foreach($matches[2] as $match) $this->css .= trim($match) ."\n";
}
}
// process css
$this->processCSS();
// create new DOMDocument
$document = new \DOMDocument('1.0', $this->getEncoding());
// set error level
libxml_use_internal_errors(true);
// load HTML
$document->loadHTML($this->html);
// create new XPath
$xPath = new \DOMXPath($document);
// any rules?
if (!empty($this->cssRules)) {
// loop rules
foreach ($this->cssRules as $rule) {
// init var
$query = $this->buildXPathQuery($rule['selector']);
// validate query
if($query === false) continue;
// search elements
$elements = $xPath->query($query);
// validate elements
if($elements === false) continue;
// loop found elements
foreach ($elements as $element) {
// no styles stored?
if ($element->attributes->getNamedItem(
'data-css-to-inline-styles-original-styles'
) == null) {
// init var
$originalStyle = '';
if ($element->attributes->getNamedItem('style') !== null) {
$originalStyle = $element->attributes->getNamedItem('style')->value;
}
// store original styles
$element->setAttribute(
'data-css-to-inline-styles-original-styles',
$originalStyle
);
// clear the styles
$element->setAttribute('style', '');
}
// init var
$properties = array();
// get current styles
$stylesAttribute = $element->attributes->getNamedItem('style');
// any styles defined before?
if ($stylesAttribute !== null) {
// get value for the styles attribute
$definedStyles = (string) $stylesAttribute->value;
// split into properties
$definedProperties = (array) explode(';', $definedStyles);
// loop properties
foreach ($definedProperties as $property) {
// validate property
if($property == '') continue;
// split into chunks
$chunks = (array) explode(':', trim($property), 2);
// validate
if(!isset($chunks[1])) continue;
// loop chunks
$properties[$chunks[0]] = trim($chunks[1]);
}
}
// add new properties into the list
foreach ($rule['properties'] as $key => $value) {
$properties[$key] = $value;
}
// build string
$propertyChunks = array();
// build chunks
foreach ($properties as $key => $values) {
foreach ((array) $values as $value) {
$propertyChunks[] = $key . ': ' . $value . ';';
}
}
// build properties string
$propertiesString = implode(' ', $propertyChunks);
// set attribute
if ($propertiesString != '') {
$element->setAttribute('style', $propertiesString);
}
}
}
// reapply original styles
$query = $this->buildXPathQuery(
'*[@data-css-to-inline-styles-original-styles]'
);
// validate query
if($query === false) return;
// search elements
$elements = $xPath->query($query);
// loop found elements
foreach ($elements as $element) {
// get the original styles
$originalStyle = $element->attributes->getNamedItem(
'data-css-to-inline-styles-original-styles'
)->value;
if ($originalStyle != '') {
$originalProperties = array();
$originalStyles = (array) explode(';', $originalStyle);
foreach ($originalStyles as $property) {
// validate property
if($property == '') continue;
// split into chunks
$chunks = (array) explode(':', trim($property), 2);
// validate
if(!isset($chunks[1])) continue;
// loop chunks
$originalProperties[$chunks[0]] = trim($chunks[1]);
}
// get current styles
$stylesAttribute = $element->attributes->getNamedItem('style');
$properties = array();
// any styles defined before?
if ($stylesAttribute !== null) {
// get value for the styles attribute
$definedStyles = (string) $stylesAttribute->value;
// split into properties
$definedProperties = (array) explode(';', $definedStyles);
// loop properties
foreach ($definedProperties as $property) {
// validate property
if($property == '') continue;
// split into chunks
$chunks = (array) explode(':', trim($property), 2);
// validate
if(!isset($chunks[1])) continue;
// loop chunks
$properties[$chunks[0]] = trim($chunks[1]);
}
}
// add new properties into the list
foreach ($originalProperties as $key => $value) {
$properties[$key] = $value;
}
// build string
$propertyChunks = array();
// build chunks
foreach ($properties as $key => $values) {
foreach ((array) $values as $value) {
$propertyChunks[] = $key . ': ' . $value . ';';
}
}
// build properties string
$propertiesString = implode(' ', $propertyChunks);
// set attribute
if($propertiesString != '') $element->setAttribute(
'style', $propertiesString
);
}
// remove placeholder
$element->removeAttribute(
'data-css-to-inline-styles-original-styles'
);
}
}
// should we output XHTML?
if ($outputXHTML) {
// set formating
$document->formatOutput = true;
// get the HTML as XML
$html = $document->saveXML(null, LIBXML_NOEMPTYTAG);
// get start of the XML-declaration
$startPosition = strpos($html, '<?xml');
// valid start position?
if ($startPosition !== false) {
// get end of the xml-declaration
$endPosition = strpos($html, '?>', $startPosition);
// remove the XML-header
$html = ltrim(substr($html, $endPosition + 1));
}
}
// just regular HTML 4.01 as it should be used in newsletters
else {
// get the HTML
$html = $document->saveHTML();
}
// cleanup the HTML if we need to
if($this->cleanup) $html = $this->cleanupHTML($html);
// strip original style tags if we need to
if ($this->stripOriginalStyleTags) {
$html = $this->stripOriginalStyleTags($html);
}
// return
return $html;
}
/**
* Get the encoding to use
*
* @return string
*/
private function getEncoding()
{
return $this->encoding;
}
/**
* Process the loaded CSS
*
* @return void
*/
private function processCSS()
{
// init vars
$css = (string) $this->css;
// remove newlines
$css = str_replace(array("\r", "\n"), '', $css);
// replace double quotes by single quotes
$css = str_replace('"', '\'', $css);
// remove comments
$css = preg_replace('|/\*.*?\*/|', '', $css);
// remove spaces
$css = preg_replace('/\s\s+/', ' ', $css);
// rules are splitted by }
$rules = (array) explode('}', $css);
// init var
$i = 1;
// loop rules
foreach ($rules as $rule) {
// split into chunks
$chunks = explode('{', $rule);
// invalid rule?
if(!isset($chunks[1])) continue;
// set the selectors
$selectors = trim($chunks[0]);
// get cssProperties
$cssProperties = trim($chunks[1]);
// split multiple selectors
$selectors = (array) explode(',', $selectors);
// loop selectors
foreach ($selectors as $selector) {
// cleanup
$selector = trim($selector);
// build an array for each selector
$ruleSet = array();
// store selector
$ruleSet['selector'] = $selector;
// process the properties
$ruleSet['properties'] = $this->processCSSProperties(
$cssProperties
);
// calculate specifity
$ruleSet['specifity'] = $this->calculateCSSSpecifity(
$selector
) + $i;
// add into global rules
$this->cssRules[] = $ruleSet;
}
// increment
$i++;
}
// sort based on specifity
if (!empty($this->cssRules)) {
usort($this->cssRules, array(__CLASS__, 'sortOnSpecifity'));
}
}
/**
* Process the CSS-properties
*
* @return array
* @param string $propertyString The CSS-properties.
*/
private function processCSSProperties($propertyString)
{
// split into chunks
$properties = (array) explode(';', $propertyString);
// init var
$pairs = array();
// loop properties
foreach ($properties as $property) {
// split into chunks
$chunks = (array) explode(':', $property, 2);
// validate
if(!isset($chunks[1])) continue;
// cleanup
$chunks[0] = trim($chunks[0]);
$chunks[1] = trim($chunks[1]);
// add to pairs array
if(!isset($pairs[$chunks[0]]) ||
!in_array($chunks[1], $pairs[$chunks[0]])) {
$pairs[$chunks[0]][] = $chunks[1];
}
}
// sort the pairs
ksort($pairs);
// return
return $pairs;
}
/**
* Should the IDs and classes be removed?
*
* @return void
* @param bool[optional] $on Should we enable cleanup?
*/
public function setCleanup($on = true)
{
$this->cleanup = (bool) $on;
}
/**
* Set CSS to use
*
* @return void
* @param string $css The CSS to use.
*/
public function setCSS($css)
{
$this->css = (string) $css;
}
/**
* Set the encoding to use with the DOMDocument
*
* @return void
* @param string $encoding The encoding to use.
*/
public function setEncoding($encoding)
{
$this->encoding = (string) $encoding;
}
/**
* Set HTML to process
*
* @return void
* @param string $html The HTML to process.
*/
public function setHTML($html)
{
$this->html = (string) $html;
}
/**
* Set use of inline styles block
* If this is enabled the class will use the style-block in the HTML.
*
* @return void
* @param bool[optional] $on Should we process inline styles?
*/
public function setUseInlineStylesBlock($on = true)
{
$this->useInlineStylesBlock = (bool) $on;
}
/**
* Set strip original style tags
* If this is enabled the class will remove all style tags in the HTML.
*
* @return void
* @param bool[optional] $onShould we process inline styles?
*/
public function setStripOriginalStyleTags($on = true)
{
$this->stripOriginalStyleTags = (bool) $on;
}
/**
* Strip style tags into the generated HTML
*
* @return string
* @param string $html The HTML to strip style tags.
*/
private function stripOriginalStyleTags($html)
{
return preg_replace('|<style(.*)>(.*)</style>|isU', '', $html);
}
/**
* Sort an array on the specifity element
*
* @return int
* @param array $e1 The first element.
* @param array $e2 The second element.
*/
private static function sortOnSpecifity($e1, $e2)
{
// validate
if(!isset($e1['specifity']) || !isset($e2['specifity'])) return 0;
// lower
if($e1['specifity'] < $e2['specifity']) return -1;
// higher
if($e1['specifity'] > $e2['specifity']) return 1;
// fallback
return 0;
}
}