source: trunk/include/emogrifier.class.php @ 27403

Last change on this file since 27403 was 27403, checked in by mistic100, 10 years ago

update emogrifier

File size: 23.7 KB
Line 
1<?php
2
3/**
4 * This class provides functions for converting CSS styles into inline style attributes in your HTML code.
5 *
6 * For more information, please see the README.md file.
7 *
8 * @author Cameron Brooks
9 * @author Jaime Prado
10 */
11class Emogrifier {
12    /**
13     * @var string
14     */
15    const ENCODING = 'UTF-8';
16
17    /**
18     * @var integer
19     */
20    const CACHE_KEY_CSS = 0;
21
22    /**
23     * @var integer
24     */
25    const CACHE_KEY_SELECTOR = 1;
26
27    /**
28     * @var integer
29     */
30    const CACHE_KEY_XPATH = 2;
31
32    /**
33     * for calculating nth-of-type and nth-child selectors
34     *
35     * @var integer
36     */
37    const INDEX = 0;
38
39    /**
40     * for calculating nth-of-type and nth-child selectors
41     *
42     * @var integer
43     */
44    const MULTIPLIER = 1;
45
46    /**
47     * @var string
48     */
49    const ID_ATTRIBUTE_MATCHER = '/(\\w+)?\\#([\\w\\-]+)/';
50
51    /**
52     * @var string
53     */
54    const CLASS_ATTRIBUTE_MATCHER = '/(\\w+|[\\*\\]])?((\\.[\\w\\-]+)+)/';
55
56    /**
57     * @var string
58     */
59    private $html = '';
60
61    /**
62     * @var string
63     */
64    private $css = '';
65
66    /**
67     * @var array<string>
68     */
69    private $unprocessableHtmlTags = array('wbr');
70
71    /**
72     * @var array<array>
73     */
74    private $caches = array(
75        self::CACHE_KEY_CSS => array(),
76        self::CACHE_KEY_SELECTOR => array(),
77        self::CACHE_KEY_XPATH => array(),
78    );
79
80    /**
81     * the visited nodes with the XPath paths as array keys
82     *
83     * @var array<\DOMNode>
84     */
85    private $visitedNodes = array();
86
87    /**
88     * the styles to apply to the nodes with the XPath paths as array keys for the outer array and the attribute names/values
89     * as key/value pairs for the inner array
90     *
91     * @var array<array><string>
92     */
93    private $styleAttributesForNodes = array();
94
95    /**
96     * This attribute applies to the case where you want to preserve your original text encoding.
97     *
98     * By default, emogrifier translates your text into HTML entities for two reasons:
99     *
100     * 1. Because of client incompatibilities, it is better practice to send out HTML entities rather than unicode over email.
101     *
102     * 2. It translates any illegal XML characters that DOMDocument cannot work with.
103     *
104     * If you would like to preserve your original encoding, set this attribute to TRUE.
105     *
106     * @var boolean
107     */
108    public $preserveEncoding = FALSE;
109
110    /**
111     * The constructor.
112     *
113     * @param string $html the HTML to emogrify, must be UTF-8-encoded
114     * @param string $css the CSS to merge, must be UTF-8-encoded
115     */
116    public function __construct($html = '', $css = '') {
117        $this->setHtml($html);
118        $this->setCss($css);
119    }
120
121    /**
122     * The destructor.
123     */
124    public function __destruct() {
125        $this->purgeVisitedNodes();
126    }
127
128    /**
129     * Sets the HTML to emogrify.
130     *
131     * @param string $html the HTML to emogrify, must be UTF-8-encoded
132     *
133     * @return void
134     */
135    public function setHtml($html = '') {
136        $this->html = $html;
137    }
138
139    /**
140     * Sets the CSS to merge with the HTML.
141     *
142     * @param string $css the CSS to merge, must be UTF-8-encoded
143     *
144     * @return void
145     */
146    public function setCss($css = '') {
147        $this->css = $css;
148    }
149
150    /**
151     * Clears all caches.
152     *
153     * @return void
154     */
155    private function clearAllCaches() {
156        $this->clearCache(self::CACHE_KEY_CSS);
157        $this->clearCache(self::CACHE_KEY_SELECTOR);
158        $this->clearCache(self::CACHE_KEY_XPATH);
159    }
160
161    /**
162     * Clears a single cache by key.
163     *
164     * @param integer $key the cache key, must be CACHE_KEY_CSS, CACHE_KEY_SELECTOR or CACHE_KEY_XPATH
165     *
166     * @return void
167     *
168     * @throws \InvalidArgumentException
169     */
170    private function clearCache($key) {
171        $allowedCacheKeys = array(self::CACHE_KEY_CSS, self::CACHE_KEY_SELECTOR, self::CACHE_KEY_XPATH);
172        if (!in_array($key, $allowedCacheKeys, TRUE)) {
173            throw new \InvalidArgumentException('Invalid cache key: ' . $key, 1391822035);
174        }
175
176        $this->caches[$key] = array();
177    }
178
179    /**
180     * Purges the visited nodes.
181     *
182     * @return void
183     */
184    private function purgeVisitedNodes() {
185        $this->visitedNodes = array();
186        $this->styleAttributesForNodes = array();
187    }
188
189    /**
190     * Marks a tag for removal.
191     *
192     * There are some HTML tags that DOMDocument cannot process, and it will throw an error if it encounters them.
193     * In particular, DOMDocument will complain if you try to use HTML5 tags in an XHTML document.
194     *
195     * Note: The tags will not be removed if they have any content.
196     *
197     * @param string $tagName the tag name, e.g., "p"
198     *
199     * @return void
200     */
201    public function addUnprocessableHtmlTag($tagName) {
202        $this->unprocessableHtmlTags[] = $tagName;
203    }
204
205    /**
206     * Drops a tag from the removal list.
207     *
208     * @param string $tagName the tag name, e.g., "p"
209     *
210     * @return void
211     */
212    public function removeUnprocessableHtmlTag($tagName) {
213        $key = array_search($tagName, $this->unprocessableHtmlTags, TRUE);
214        if ($key !== FALSE) {
215            unset($this->unprocessableHtmlTags[$key]);
216        }
217    }
218
219    /**
220     * Applies the CSS you submit to the HTML you submit.
221     *
222     * This method places the CSS inline.
223     *
224     * @return string
225     *
226     * @throws \BadMethodCallException
227     */
228    public function emogrify() {
229        if ($this->html === '') {
230            throw new \BadMethodCallException('Please set some HTML first before calling emogrify.', 1390393096);
231        }
232
233        $xmlDocument = $this->createXmlDocument();
234        $xpath = new \DOMXPath($xmlDocument);
235        $this->clearAllCaches();
236
237        // before be begin processing the CSS file, parse the document and normalize all existing CSS attributes (changes 'DISPLAY: none' to 'display: none');
238        // we wouldn't have to do this if DOMXPath supported XPath 2.0.
239        // also store a reference of nodes with existing inline styles so we don't overwrite them
240        $this->purgeVisitedNodes();
241
242        $nodesWithStyleAttributes = $xpath->query('//*[@style]');
243        if ($nodesWithStyleAttributes !== FALSE) {
244            $callback = create_function('$m', 'return strtolower($m[0]);');
245
246            /** @var $nodeWithStyleAttribute \DOMNode */
247            foreach ($nodesWithStyleAttributes as $node) {
248                $normalizedOriginalStyle = preg_replace_callback(
249                    '/[A-z\\-]+(?=\\:)/S',
250                    $callback,
251                    $node->getAttribute('style')
252                );
253
254                // in order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles
255                $nodePath = $node->getNodePath();
256                if (!isset($this->styleAttributesForNodes[$nodePath])) {
257                    $this->styleAttributesForNodes[$nodePath] = $this->parseCssDeclarationBlock($normalizedOriginalStyle);
258                    $this->visitedNodes[$nodePath] = $node;
259                }
260
261                $node->setAttribute('style', $normalizedOriginalStyle);
262            }
263        }
264
265        // grab any existing style blocks from the html and append them to the existing CSS
266        // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
267        $css = $this->css;
268        $styleNodes = $xpath->query('//style');
269        if ($styleNodes !== FALSE) {
270            /** @var $styleNode \DOMNode */
271            foreach ($styleNodes as $styleNode) {
272                // append the css
273                $css .= "\n\n" . $styleNode->nodeValue;
274                // remove the <style> node
275                $styleNode->parentNode->removeChild($styleNode);
276            }
277        }
278
279        // filter the CSS
280        $search = array(
281            // get rid of css comment code
282            '/\\/\\*.*\\*\\//sU',
283            // strip out any import directives
284            '/^\\s*@import\\s[^;]+;/misU',
285            // strip any empty media enclosures
286            '/^\\s*@media\\s[^{]+{\\s*}/misU',
287            // strip out all media rules that are not 'screen' or 'all' (these don't apply to email)
288            '/^\\s*@media\\s+((aural|braille|embossed|handheld|print|projection|speech|tty|tv)\\s*,*\\s*)+{.*}\\s*}/misU',
289            // get rid of remaining media type rules
290            '/^\\s*@media\\s[^{]+{(.*})\\s*}/misU',
291        );
292
293        $replace = array(
294            '',
295            '',
296            '',
297            '',
298            '\\1',
299        );
300
301        $css = preg_replace($search, $replace, $css);
302
303        $cssKey = md5($css);
304        if (!isset($this->caches[self::CACHE_KEY_CSS][$cssKey])) {
305            // process the CSS file for selectors and definitions
306            preg_match_all('/(?:^|[^{}])\\s*([^{]+){([^}]*)}/mis', $css, $matches, PREG_SET_ORDER);
307
308            $allSelectors = array();
309            foreach ($matches as $key => $selectorString) {
310                // if there is a blank definition, skip
311                if (!strlen(trim($selectorString[2]))) {
312                    continue;
313                }
314
315                // else split by commas and duplicate attributes so we can sort by selector precedence
316                $selectors = explode(',', $selectorString[1]);
317                foreach ($selectors as $selector) {
318                    // don't process pseudo-elements and behavioral (dynamic) pseudo-classes; ONLY allow structural pseudo-classes
319                    if (strpos($selector, ':') !== FALSE && !preg_match('/:\\S+\\-(child|type)\\(/i', $selector)) {
320                        continue;
321                    }
322
323                    $allSelectors[] = array('selector' => trim($selector),
324                                             'attributes' => trim($selectorString[2]),
325                                             // keep track of where it appears in the file, since order is important
326                                             'line' => $key,
327                    );
328                }
329            }
330
331            // now sort the selectors by precedence
332            usort($allSelectors, array($this,'sortBySelectorPrecedence'));
333
334            $this->caches[self::CACHE_KEY_CSS][$cssKey] = $allSelectors;
335        }
336
337        foreach ($this->caches[self::CACHE_KEY_CSS][$cssKey] as $value) {
338            // query the body for the xpath selector
339            $nodesMatchingCssSelectors = $xpath->query($this->translateCssToXpath(trim($value['selector'])));
340
341            /** @var $node \DOMNode */
342            foreach ($nodesMatchingCssSelectors as $node) {
343                // if it has a style attribute, get it, process it, and append (overwrite) new stuff
344                if ($node->hasAttribute('style')) {
345                    // break it up into an associative array
346                    $oldStyleDeclarations = $this->parseCssDeclarationBlock($node->getAttribute('style'));
347                    $newStyleDeclarations = $this->parseCssDeclarationBlock($value['attributes']);
348
349                    // new styles overwrite the old styles (not technically accurate, but close enough)
350                    $combinedArray = array_merge($oldStyleDeclarations, $newStyleDeclarations);
351                    $style = '';
352                    foreach ($combinedArray as $attributeName => $attributeValue) {
353                        $style .= (strtolower($attributeName) . ':' . $attributeValue . ';');
354                    }
355                } else {
356                    // otherwise create a new style
357                    $style = trim($value['attributes']);
358                }
359                $node->setAttribute('style', $style);
360            }
361        }
362
363        // now iterate through the nodes that contained inline styles in the original HTML
364        foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
365            $node = $this->visitedNodes[$nodePath];
366            $currentStyleAttributes = $this->parseCssDeclarationBlock($node->getAttribute('style'));
367
368            $combinedArray = array_merge($currentStyleAttributes, $styleAttributesForNode);
369            $style = '';
370            foreach ($combinedArray as $attributeName => $attributeValue) {
371                $style .= (strtolower($attributeName) . ':' . $attributeValue . ';');
372            }
373
374            $node->setAttribute('style', $style);
375        }
376
377        // This removes styles from your email that contain display:none.
378        // We need to look for display:none, but we need to do a case-insensitive search. Since DOMDocument only supports XPath 1.0,
379        // lower-case() isn't available to us. We've thus far only set attributes to lowercase, not attribute values. Consequently, we need
380        // to translate() the letters that would be in 'NONE' ("NOE") to lowercase.
381        $nodesWithStyleDisplayNone = $xpath->query('//*[contains(translate(translate(@style," ",""),"NOE","noe"),"display:none")]');
382        // The checks on parentNode and is_callable below ensure that if we've deleted the parent node,
383        // we don't try to call removeChild on a nonexistent child node
384        if ($nodesWithStyleDisplayNone->length > 0) {
385            /** @var $node \DOMNode */
386            foreach ($nodesWithStyleDisplayNone as $node) {
387                if ($node->parentNode && is_callable(array($node->parentNode,'removeChild'))) {
388                    $node->parentNode->removeChild($node);
389                }
390            }
391        }
392
393        if ($this->preserveEncoding) {
394            return mb_convert_encoding($xmlDocument->saveHTML(), self::ENCODING, 'HTML-ENTITIES');
395        } else {
396            return $xmlDocument->saveHTML();
397        }
398    }
399
400    /**
401     * Creates a DOMDocument instance with the current HTML.
402     *
403     * @return \DOMDocument
404     */
405    private function createXmlDocument() {
406        $xmlDocument = new \DOMDocument;
407        $xmlDocument->encoding = self::ENCODING;
408        $xmlDocument->strictErrorChecking = FALSE;
409        $xmlDocument->formatOutput = TRUE;
410        $libxmlState = libxml_use_internal_errors(TRUE);
411        $xmlDocument->loadHTML($this->getUnifiedHtml());
412        libxml_clear_errors();
413        libxml_use_internal_errors($libxmlState);
414        $xmlDocument->normalizeDocument();
415
416        return $xmlDocument;
417    }
418
419    /**
420     * Returns the HTML with the non-ASCII characters converts into HTML entities and the unprocessable HTML tags removed.
421     *
422     * @return string the unified HTML
423     *
424     * @throws \BadMethodCallException
425     */
426    private function getUnifiedHtml() {
427        if (!empty($this->unprocessableHtmlTags)) {
428            $unprocessableHtmlTags = implode('|', $this->unprocessableHtmlTags);
429            $bodyWithoutUnprocessableTags = preg_replace('/<\\/?(' . $unprocessableHtmlTags . ')[^>]*>/i', '', $this->html);
430        } else {
431            $bodyWithoutUnprocessableTags = $this->html;
432        }
433
434        return mb_convert_encoding($bodyWithoutUnprocessableTags, 'HTML-ENTITIES', self::ENCODING);
435    }
436
437    /**
438     * @param array $a
439     * @param array $b
440     *
441     * @return integer
442     */
443    private function sortBySelectorPrecedence(array $a, array $b) {
444        $precedenceA = $this->getCssSelectorPrecedence($a['selector']);
445        $precedenceB = $this->getCssSelectorPrecedence($b['selector']);
446
447        // We want these sorted in ascending order so selectors with lesser precedence get processed first and
448        // selectors with greater precedence get sorted last.
449        // The parenthesis around the -1 are necessary to avoid a PHP_CodeSniffer warning about missing spaces around
450        // arithmetic operators.
451        // @see http://forge.typo3.org/issues/55605
452        $precedenceForEquals = ($a['line'] < $b['line'] ? (-1) : 1);
453        $precedenceForNotEquals = ($precedenceA < $precedenceB ? (-1) : 1);
454        return ($precedenceA === $precedenceB) ? $precedenceForEquals : $precedenceForNotEquals;
455    }
456
457    /**
458     * @param string $selector
459     *
460     * @return integer
461     */
462    private function getCssSelectorPrecedence($selector) {
463        $selectorKey = md5($selector);
464        if (!isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) {
465            $precedence = 0;
466            $value = 100;
467            // ids: worth 100, classes: worth 10, elements: worth 1
468            $search = array('\\#','\\.','');
469
470            foreach ($search as $s) {
471                if (trim($selector == '')) {
472                    break;
473                }
474                $number = 0;
475                $selector = preg_replace('/' . $s . '\\w+/', '', $selector, -1, $number);
476                $precedence += ($value * $number);
477                $value /= 10;
478            }
479            $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
480        }
481
482        return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey];
483    }
484
485    /**
486     * Right now, we support all CSS 1 selectors and most CSS2/3 selectors.
487     *
488     * @see http://plasmasturm.org/log/444/
489     *
490     * @param string $cssSelector
491     *
492     * @return string
493     */
494    private function translateCssToXpath($cssSelector) {
495        $cssSelector = trim($cssSelector);
496        $xpathKey = md5($cssSelector);
497        if (!isset($this->caches[self::CACHE_KEY_XPATH][$xpathKey])) {
498            // returns an Xpath selector
499            $search = array(
500                // Matches any element that is a child of parent.
501                '/\\s+>\\s+/',
502                // Matches any element that is an adjacent sibling.
503                '/\\s+\\+\\s+/',
504                // Matches any element that is a descendant of an parent element element.
505                '/\\s+/',
506                // first-child pseudo-selector
507                '/([^\\/]+):first-child/i',
508                // last-child pseudo-selector
509                '/([^\\/]+):last-child/i',
510                // Matches element with attribute
511                '/(\\w)\\[(\\w+)\\]/',
512                // Matches element with EXACT attribute
513                '/(\\w)\\[(\\w+)\\=[\'"]?(\\w+)[\'"]?\\]/',
514            );
515            $replace = array(
516                '/',
517                '/following-sibling::*[1]/self::',
518                '//',
519                '*[1]/self::\\1',
520                '*[last()]/self::\\1',
521                '\\1[@\\2]',
522                '\\1[@\\2="\\3"]',
523            );
524
525            $cssSelector = '//' . preg_replace($search, $replace, $cssSelector);
526
527            $cssSelector = preg_replace_callback(self::ID_ATTRIBUTE_MATCHER, array($this, 'matchIdAttributes'), $cssSelector);
528            $cssSelector = preg_replace_callback(self::CLASS_ATTRIBUTE_MATCHER, array($this, 'matchClassAttributes'), $cssSelector);
529
530            // Advanced selectors are going to require a bit more advanced emogrification.
531            // When we required PHP 5.3, we could do this with closures.
532            $cssSelector = preg_replace_callback(
533                '/([^\\/]+):nth-child\\(\s*(odd|even|[+\-]?\\d|[+\\-]?\\d?n(\\s*[+\\-]\\s*\\d)?)\\s*\\)/i',
534                array($this, 'translateNthChild'), $cssSelector
535            );
536            $cssSelector = preg_replace_callback(
537                '/([^\\/]+):nth-of-type\\(\s*(odd|even|[+\-]?\\d|[+\\-]?\\d?n(\\s*[+\\-]\\s*\\d)?)\\s*\\)/i',
538                array($this, 'translateNthOfType'), $cssSelector
539            );
540
541            $this->caches[self::CACHE_KEY_SELECTOR][$xpathKey] = $cssSelector;
542        }
543        return $this->caches[self::CACHE_KEY_SELECTOR][$xpathKey];
544    }
545
546    /**
547     * @param array $match
548     *
549     * @return string
550     */
551    private function matchIdAttributes(array $match) {
552        return (strlen($match[1]) ? $match[1] : '*') . '[@id="' . $match[2] . '"]';
553    }
554
555    /**
556     * @param array $match
557     *
558     * @return string
559     */
560    private function matchClassAttributes(array $match) {
561        return (strlen($match[1]) ? $match[1] : '*') . '[contains(concat(" ",@class," "),concat(" ","' .
562            implode(
563                '"," "))][contains(concat(" ",@class," "),concat(" ","',
564                explode('.', substr($match[2], 1))
565            ) . '"," "))]';
566    }
567
568    /**
569     * @param array $match
570     *
571     * @return string
572     */
573    private function translateNthChild(array $match) {
574        $result = $this->parseNth($match);
575
576        if (isset($result[self::MULTIPLIER])) {
577            if ($result[self::MULTIPLIER] < 0) {
578                $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
579                return sprintf('*[(last() - position()) mod %u = %u]/self::%s', $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
580            } else {
581                return sprintf('*[position() mod %u = %u]/self::%s', $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
582            }
583        } else {
584            return sprintf('*[%u]/self::%s', $result[self::INDEX], $match[1]);
585        }
586    }
587
588    /**
589     * @param array $match
590     *
591     * @return string
592     */
593    private function translateNthOfType(array $match) {
594        $result = $this->parseNth($match);
595
596        if (isset($result[self::MULTIPLIER])) {
597            if ($result[self::MULTIPLIER] < 0) {
598                $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
599                return sprintf('%s[(last() - position()) mod %u = %u]', $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
600            } else {
601                return sprintf('%s[position() mod %u = %u]', $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
602            }
603        } else {
604            return sprintf('%s[%u]', $match[1], $result[self::INDEX]);
605        }
606    }
607
608    /**
609     * @param array $match
610     *
611     * @return array
612     */
613    private function parseNth(array $match) {
614        if (in_array(strtolower($match[2]), array('even','odd'))) {
615            $index = strtolower($match[2]) == 'even' ? 0 : 1;
616            return array(self::MULTIPLIER => 2, self::INDEX => $index);
617        } elseif (stripos($match[2], 'n') === FALSE) {
618            // if there is a multiplier
619            $index = intval(str_replace(' ', '', $match[2]));
620            return array(self::INDEX => $index);
621        } else {
622            if (isset($match[3])) {
623                $multipleTerm = str_replace($match[3], '', $match[2]);
624                $index = intval(str_replace(' ', '', $match[3]));
625            } else {
626                $multipleTerm = $match[2];
627                $index = 0;
628            }
629
630            $multiplier = str_ireplace('n', '', $multipleTerm);
631
632            if (!strlen($multiplier)) {
633                $multiplier = 1;
634            } elseif ($multiplier == 0) {
635                return array(self::INDEX => $index);
636            } else {
637                $multiplier = intval($multiplier);
638            }
639
640            while ($index < 0) {
641                $index += abs($multiplier);
642            }
643
644            return array(self::MULTIPLIER => $multiplier, self::INDEX => $index);
645        }
646    }
647
648    /**
649     * Parses a CSS declaration block into property name/value pairs.
650     *
651     * Example:
652     *
653     * The declaration block
654     *
655     *   "color: #000; font-weight: bold;"
656     *
657     * will be parsed into the following array:
658     *
659     *   "color" => "#000"
660     *   "font-weight" => "bold"
661     *
662     * @param string $cssDeclarationBlock the CSS declaration block without the curly braces, may be empty
663     *
664     * @return array the CSS declarations with the property names as array keys and the property values as array values
665     */
666    private function parseCssDeclarationBlock($cssDeclarationBlock) {
667        $properties = array();
668
669        $declarations = explode(';', $cssDeclarationBlock);
670        foreach ($declarations as $declaration) {
671            $matches = array();
672            if (!preg_match('/ *([a-z\-]+) *: *([^;]+) */', $declaration, $matches)) {
673                continue;
674            }
675            $propertyName = $matches[1];
676            $propertyValue = $matches[2];
677            $properties[$propertyName] = $propertyValue;
678        }
679
680        return $properties;
681    }
682}
Note: See TracBrowser for help on using the repository browser.