emogrifier.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /*
  3. UPDATES
  4. 2008-08-10 Fixed CSS comment stripping regex to add PCRE_DOTALL (changed from '/\/\*.*\*\//U' to '/\/\*.*\*\//sU')
  5. 2008-08-18 Added lines instructing DOMDocument to attempt to normalize HTML before processing
  6. 2008-10-20 Fixed bug with bad variable name... Thanks Thomas!
  7. 2008-03-02 Added licensing terms under the MIT License
  8. Only remove unprocessable HTML tags if they exist in the array
  9. 2009-06-03 Normalize existing CSS (style) attributes in the HTML before we process the CSS.
  10. Made it so that the display:none stripper doesn't require a trailing semi-colon.
  11. 2009-08-13 Added support for subset class values (e.g. "p.class1.class2").
  12. Added better protection for bad css attributes.
  13. Fixed support for HTML entities.
  14. 2009-08-17 Fixed CSS selector processing so that selectors are processed by precedence/specificity, and not just in order.
  15. 2009-10-29 Fixed so that selectors appearing later in the CSS will have precedence over identical selectors appearing earlier.
  16. 2009-11-04 Explicitly declared static functions static to get rid of E_STRICT notices.
  17. 2010-05-18 Fixed bug where full url filenames with protocols wouldn't get split improperly when we explode on ':'... Thanks Mark!
  18. Added two new attribute selectors
  19. 2010-06-16 Added static caching for less processing overhead in situations where multiple emogrification takes place
  20. 2010-07-26 Fixed bug where '0' values were getting discarded because of php's empty() function... Thanks Scott!
  21. 2010-09-03 Added checks to invisible node removal to ensure that we don't try to remove non-existent child nodes of parents that have already been deleted
  22. 2011-04-08 Fixed errors in CSS->XPath conversion for adjacent sibling selectors and id/class combinations... Thanks Bob V.!
  23. 2011-06-08 Fixed an error where CSS @media types weren't being parsed correctly... Thanks Will W.!
  24. 2011-08-03 Fixed an error where an empty selector at the beginning of the CSS would cause a parse error on the next selector... Thanks Alexei T.!
  25. 2011-10-13 Fully fixed a bug introduced in 2011-06-08 where selectors at the beginning of the CSS would be parsed incorrectly... Thanks Thomas A.!
  26. 2011-10-26 Added an option to allow you to output emogrified code without extended characters being turned into HTML entities.
  27. Moved static references to class attributes so they can be manipulated.
  28. Added the ability to clear out the (formerly) static cache when CSS is reloaded.
  29. 2011-12-22 Fixed a bug that was overwriting existing inline styles from the original HTML... Thanks Sagi L.!
  30. 2012-01-31 Fixed a bug that was introduced with the 2011-12-22 revision... Thanks Sagi L. and M. Bąkowski!
  31. Added extraction of <style> blocks within the HTML due to popular demand.
  32. Added several new pseudo-selectors (first-child, last-child, nth-child, and nth-of-type).
  33. 2012-02-07 Fixed some recent code introductions to use class constants rather than global constants.
  34. Fixed some recent code introductions to make it cleaner to read.
  35. 2012-05-01 Made removal of invisible nodes operate in a case-insensitive manner... Thanks Juha P.!
  36. */
  37. define('CACHE_CSS', 0);
  38. define('CACHE_SELECTOR', 1);
  39. define('CACHE_XPATH', 2);
  40. class Emogrifier {
  41. // for calculating nth-of-type and nth-child selectors
  42. const INDEX = 0;
  43. const MULTIPLIER = 1;
  44. private $html = '';
  45. private $css = '';
  46. private $unprocessableHTMLTags = array('wbr');
  47. private $caches = array();
  48. // this attribute applies to the case where you want to preserve your original text encoding.
  49. // by default, emogrifier translates your text into HTML entities for two reasons:
  50. // 1. because of client incompatibilities, it is better practice to send out HTML entities rather than unicode over email
  51. // 2. it translates any illegal XML characters that DOMDocument cannot work with
  52. // if you would like to preserve your original encoding, set this attribute to true.
  53. public $preserveEncoding = false;
  54. public function __construct($html = '', $css = '') {
  55. $this->html = $html;
  56. $this->css = $css;
  57. $this->clearCache();
  58. }
  59. public function setHTML($html = '') { $this->html = $html; }
  60. public function setCSS($css = '') {
  61. $this->css = $css;
  62. $this->clearCache(CACHE_CSS);
  63. }
  64. public function clearCache($key = null) {
  65. if (!is_null($key)) {
  66. if (isset($this->caches[$key])) $this->caches[$key] = array();
  67. } else {
  68. $this->caches = array(
  69. CACHE_CSS => array(),
  70. CACHE_SELECTOR => array(),
  71. CACHE_XPATH => array(),
  72. );
  73. }
  74. }
  75. // there are some HTML tags that DOMDocument cannot process, and will throw an error if it encounters them.
  76. // in particular, DOMDocument will complain if you try to use HTML5 tags in an XHTML document.
  77. // these functions allow you to add/remove them if necessary.
  78. // it only strips them from the code (does not remove actual nodes).
  79. public function addUnprocessableHTMLTag($tag) { $this->unprocessableHTMLTags[] = $tag; }
  80. public function removeUnprocessableHTMLTag($tag) {
  81. if (($key = array_search($tag,$this->unprocessableHTMLTags)) !== false)
  82. unset($this->unprocessableHTMLTags[$key]);
  83. }
  84. // applies the CSS you submit to the html you submit. places the css inline
  85. public function emogrify() {
  86. $body = $this->html;
  87. // remove any unprocessable HTML tags (tags that DOMDocument cannot parse; this includes wbr and many new HTML5 tags)
  88. if (count($this->unprocessableHTMLTags)) {
  89. $unprocessableHTMLTags = implode('|',$this->unprocessableHTMLTags);
  90. $body = preg_replace("/<\/?($unprocessableHTMLTags)[^>]*>/i",'',$body);
  91. }
  92. $encoding = mb_detect_encoding($body);
  93. $body = mb_convert_encoding($body, 'HTML-ENTITIES', $encoding);
  94. $xmldoc = new DOMDocument;
  95. $xmldoc->encoding = $encoding;
  96. $xmldoc->strictErrorChecking = false;
  97. $xmldoc->formatOutput = true;
  98. $xmldoc->loadHTML($body);
  99. $xmldoc->normalizeDocument();
  100. $xpath = new DOMXPath($xmldoc);
  101. // before be begin processing the CSS file, parse the document and normalize all existing CSS attributes (changes 'DISPLAY: none' to 'display: none');
  102. // we wouldn't have to do this if DOMXPath supported XPath 2.0.
  103. // also store a reference of nodes with existing inline styles so we don't overwrite them
  104. $vistedNodes = $vistedNodeRef = array();
  105. $nodes = @$xpath->query('//*[@style]');
  106. foreach ($nodes as $node) {
  107. $normalizedOrigStyle = preg_replace('/[A-z\-]+(?=\:)/Se',"strtolower('\\0')", $node->getAttribute('style'));
  108. // in order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles
  109. $nodeKey = md5($node->getNodePath());
  110. if (!isset($vistedNodeRef[$nodeKey])) {
  111. $vistedNodeRef[$nodeKey] = $this->cssStyleDefinitionToArray($normalizedOrigStyle);
  112. $vistedNodes[$nodeKey] = $node;
  113. }
  114. $node->setAttribute('style', $normalizedOrigStyle);
  115. }
  116. // grab any existing style blocks from the html and append them to the existing CSS
  117. // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
  118. $css = $this->css;
  119. $nodes = @$xpath->query('//style');
  120. foreach ($nodes as $node) {
  121. // append the css
  122. $css .= "\n\n{$node->nodeValue}";
  123. // remove the <style> node
  124. $node->parentNode->removeChild($node);
  125. }
  126. // filter the CSS
  127. $search = array(
  128. '/\/\*.*\*\//sU', // get rid of css comment code
  129. '/^\s*@import\s[^;]+;/misU', // strip out any import directives
  130. '/^\s*@media\s[^{]+{\s*}/misU', // strip any empty media enclosures
  131. '/^\s*@media\s+((aural|braille|embossed|handheld|print|projection|speech|tty|tv)\s*,*\s*)+{.*}\s*}/misU', // strip out all media types that are not 'screen' or 'all' (these don't apply to email)
  132. '/^\s*@media\s[^{]+{(.*})\s*}/misU', // get rid of remaining media type enclosures
  133. );
  134. $replace = array(
  135. '',
  136. '',
  137. '',
  138. '',
  139. '\\1',
  140. );
  141. $css = preg_replace($search, $replace, $css);
  142. $csskey = md5($css);
  143. if (!isset($this->caches[CACHE_CSS][$csskey])) {
  144. // process the CSS file for selectors and definitions
  145. preg_match_all('/(^|[^{}])\s*([^{]+){([^}]*)}/mis', $css, $matches, PREG_SET_ORDER);
  146. $all_selectors = array();
  147. foreach ($matches as $key => $selectorString) {
  148. // if there is a blank definition, skip
  149. if (!strlen(trim($selectorString[3]))) continue;
  150. // else split by commas and duplicate attributes so we can sort by selector precedence
  151. $selectors = explode(',',$selectorString[2]);
  152. foreach ($selectors as $selector) {
  153. // don't process pseudo-elements and behavioral (dynamic) pseudo-classes; ONLY allow structural pseudo-classes
  154. if (strpos($selector, ':') !== false && !preg_match('/:\S+\-(child|type)\(/i', $selector)) continue;
  155. $all_selectors[] = array('selector' => trim($selector),
  156. 'attributes' => trim($selectorString[3]),
  157. 'line' => $key, // keep track of where it appears in the file, since order is important
  158. );
  159. }
  160. }
  161. // now sort the selectors by precedence
  162. usort($all_selectors, array($this,'sortBySelectorPrecedence'));
  163. $this->caches[CACHE_CSS][$csskey] = $all_selectors;
  164. }
  165. foreach ($this->caches[CACHE_CSS][$csskey] as $value) {
  166. // query the body for the xpath selector
  167. $nodes = $xpath->query($this->translateCSStoXpath(trim($value['selector'])));
  168. foreach($nodes as $node) {
  169. // if it has a style attribute, get it, process it, and append (overwrite) new stuff
  170. if ($node->hasAttribute('style')) {
  171. // break it up into an associative array
  172. $oldStyleArr = $this->cssStyleDefinitionToArray($node->getAttribute('style'));
  173. $newStyleArr = $this->cssStyleDefinitionToArray($value['attributes']);
  174. // new styles overwrite the old styles (not technically accurate, but close enough)
  175. $combinedArr = array_merge($oldStyleArr,$newStyleArr);
  176. $style = '';
  177. foreach ($combinedArr as $k => $v) $style .= (strtolower($k) . ':' . $v . ';');
  178. } else {
  179. // otherwise create a new style
  180. $style = trim($value['attributes']);
  181. }
  182. $node->setAttribute('style', $style);
  183. }
  184. }
  185. // now iterate through the nodes that contained inline styles in the original HTML
  186. foreach ($vistedNodeRef as $nodeKey => $origStyleArr) {
  187. $node = $vistedNodes[$nodeKey];
  188. $currStyleArr = $this->cssStyleDefinitionToArray($node->getAttribute('style'));
  189. $combinedArr = array_merge($currStyleArr, $origStyleArr);
  190. $style = '';
  191. foreach ($combinedArr as $k => $v) $style .= (strtolower($k) . ':' . $v . ';');
  192. $node->setAttribute('style', $style);
  193. }
  194. // This removes styles from your email that contain display:none.
  195. // We need to look for display:none, but we need to do a case-insensitive search. Since DOMDocument only supports XPath 1.0,
  196. // lower-case() isn't available to us. We've thus far only set attributes to lowercase, not attribute values. Consequently, we need
  197. // to translate() the letters that would be in 'NONE' ("NOE") to lowercase.
  198. $nodes = $xpath->query('//*[contains(translate(translate(@style," ",""),"NOE","noe"),"display:none")]');
  199. // The checks on parentNode and is_callable below ensure that if we've deleted the parent node,
  200. // we don't try to call removeChild on a nonexistent child node
  201. if ($nodes->length > 0)
  202. foreach ($nodes as $node)
  203. if ($node->parentNode && is_callable(array($node->parentNode,'removeChild')))
  204. $node->parentNode->removeChild($node);
  205. if ($this->preserveEncoding) {
  206. return mb_convert_encoding($xmldoc->saveHTML(), $encoding, 'HTML-ENTITIES');
  207. } else {
  208. return $xmldoc->saveHTML();
  209. }
  210. }
  211. private function sortBySelectorPrecedence($a, $b) {
  212. $precedenceA = $this->getCSSSelectorPrecedence($a['selector']);
  213. $precedenceB = $this->getCSSSelectorPrecedence($b['selector']);
  214. // we want these sorted ascendingly so selectors with lesser precedence get processed first and
  215. // selectors with greater precedence get sorted last
  216. return ($precedenceA == $precedenceB) ? ($a['line'] < $b['line'] ? -1 : 1) : ($precedenceA < $precedenceB ? -1 : 1);
  217. }
  218. private function getCSSSelectorPrecedence($selector) {
  219. $selectorkey = md5($selector);
  220. if (!isset($this->caches[CACHE_SELECTOR][$selectorkey])) {
  221. $precedence = 0;
  222. $value = 100;
  223. $search = array('\#','\.',''); // ids: worth 100, classes: worth 10, elements: worth 1
  224. foreach ($search as $s) {
  225. if (trim($selector == '')) break;
  226. $num = 0;
  227. $selector = preg_replace('/'.$s.'\w+/','',$selector,-1,$num);
  228. $precedence += ($value * $num);
  229. $value /= 10;
  230. }
  231. $this->caches[CACHE_SELECTOR][$selectorkey] = $precedence;
  232. }
  233. return $this->caches[CACHE_SELECTOR][$selectorkey];
  234. }
  235. // right now we support all CSS 1 selectors and most CSS2/3 selectors.
  236. // http://plasmasturm.org/log/444/
  237. private function translateCSStoXpath($css_selector) {
  238. $css_selector = trim($css_selector);
  239. $xpathkey = md5($css_selector);
  240. if (!isset($this->caches[CACHE_XPATH][$xpathkey])) {
  241. // returns an Xpath selector
  242. $search = array(
  243. '/\s+>\s+/', // Matches any element that is a child of parent.
  244. '/\s+\+\s+/', // Matches any element that is an adjacent sibling.
  245. '/\s+/', // Matches any element that is a descendant of an parent element element.
  246. '/([^\/]+):first-child/i', // first-child pseudo-selector
  247. '/([^\/]+):last-child/i', // last-child pseudo-selector
  248. '/(\w)\[(\w+)\]/', // Matches element with attribute
  249. '/(\w)\[(\w+)\=[\'"]?(\w+)[\'"]?\]/', // Matches element with EXACT attribute
  250. '/(\w+)?\#([\w\-]+)/e', // Matches id attributes
  251. '/(\w+|[\*\]])?((\.[\w\-]+)+)/e', // Matches class attributes
  252. );
  253. $replace = array(
  254. '/',
  255. '/following-sibling::*[1]/self::',
  256. '//',
  257. '*[1]/self::\\1',
  258. '*[last()]/self::\\1',
  259. '\\1[@\\2]',
  260. '\\1[@\\2="\\3"]',
  261. "(strlen('\\1') ? '\\1' : '*').'[@id=\"\\2\"]'",
  262. "(strlen('\\1') ? '\\1' : '*').'[contains(concat(\" \",@class,\" \"),concat(\" \",\"'.implode('\",\" \"))][contains(concat(\" \",@class,\" \"),concat(\" \",\"',explode('.',substr('\\2',1))).'\",\" \"))]'",
  263. );
  264. $css_selector = '//'.preg_replace($search, $replace, $css_selector);
  265. // advanced selectors are going to require a bit more advanced emogrification
  266. // if we required PHP 5.3 we could do this with closures
  267. $css_selector = preg_replace_callback('/([^\/]+):nth-child\(\s*(odd|even|[+\-]?\d|[+\-]?\d?n(\s*[+\-]\s*\d)?)\s*\)/i', array($this, 'translateNthChild'), $css_selector);
  268. $css_selector = preg_replace_callback('/([^\/]+):nth-of-type\(\s*(odd|even|[+\-]?\d|[+\-]?\d?n(\s*[+\-]\s*\d)?)\s*\)/i', array($this, 'translateNthOfType'), $css_selector);
  269. $this->caches[CACHE_SELECTOR][$xpathkey] = $css_selector;
  270. }
  271. return $this->caches[CACHE_SELECTOR][$xpathkey];
  272. }
  273. private function translateNthChild($match) {
  274. $result = $this->parseNth($match);
  275. if (isset($result[self::MULTIPLIER])) {
  276. if ($result[self::MULTIPLIER] < 0) {
  277. $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
  278. return sprintf("*[(last() - position()) mod %u = %u]/self::%s", $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
  279. } else {
  280. return sprintf("*[position() mod %u = %u]/self::%s", $result[self::MULTIPLIER], $result[self::INDEX], $match[1]);
  281. }
  282. } else {
  283. return sprintf("*[%u]/self::%s", $result[self::INDEX], $match[1]);
  284. }
  285. }
  286. private function translateNthOfType($match) {
  287. $result = $this->parseNth($match);
  288. if (isset($result[self::MULTIPLIER])) {
  289. if ($result[self::MULTIPLIER] < 0) {
  290. $result[self::MULTIPLIER] = abs($result[self::MULTIPLIER]);
  291. return sprintf("%s[(last() - position()) mod %u = %u]", $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
  292. } else {
  293. return sprintf("%s[position() mod %u = %u]", $match[1], $result[self::MULTIPLIER], $result[self::INDEX]);
  294. }
  295. } else {
  296. return sprintf("%s[%u]", $match[1], $result[self::INDEX]);
  297. }
  298. }
  299. private function parseNth($match) {
  300. if (in_array(strtolower($match[2]), array('even','odd'))) {
  301. $index = strtolower($match[2]) == 'even' ? 0 : 1;
  302. return array(self::MULTIPLIER => 2, self::INDEX => $index);
  303. // if there is a multiplier
  304. } else if (stripos($match[2], 'n') === false) {
  305. $index = intval(str_replace(' ', '', $match[2]));
  306. return array(self::INDEX => $index);
  307. } else {
  308. if (isset($match[3])) {
  309. $multiple_term = str_replace($match[3], '', $match[2]);
  310. $index = intval(str_replace(' ', '', $match[3]));
  311. } else {
  312. $multiple_term = $match[2];
  313. $index = 0;
  314. }
  315. $multiplier = str_ireplace('n', '', $multiple_term);
  316. if (!strlen($multiplier)) $multiplier = 1;
  317. elseif ($multiplier == 0) return array(self::INDEX => $index);
  318. else $multiplier = intval($multiplier);
  319. while ($index < 0) $index += abs($multiplier);
  320. return array(self::MULTIPLIER => $multiplier, self::INDEX => $index);
  321. }
  322. }
  323. private function cssStyleDefinitionToArray($style) {
  324. $definitions = explode(';',$style);
  325. $retArr = array();
  326. foreach ($definitions as $def) {
  327. if (empty($def) || strpos($def, ':') === false) continue;
  328. list($key,$value) = explode(':',$def,2);
  329. if (empty($key) || strlen(trim($value)) === 0) continue;
  330. $retArr[trim($key)] = trim($value);
  331. }
  332. return $retArr;
  333. }
  334. }