PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/com_acymailing_starter_2.0.0_2011-07-06/front/inc/emogrifier/emogrifier.php

https://gitlab.com/endomorphosis/OLAAaction
PHP | 228 lines | 144 code | 33 blank | 51 comment | 23 complexity | d8923498f07faef09e0837eab34def58 MD5 | raw file
  1. <?php defined('_JEXEC') or die('Restricted access'); ?>
  2. <?php
  3. /*
  4. UPDATES
  5. 2008-08-10 Fixed CSS comment stripping regex to add PCRE_DOTALL (changed from '/\/\*.*\*\//U' to '/\/\*.*\*\//sU')
  6. 2008-08-18 Added lines instructing DOMDocument to attempt to normalize HTML before processing
  7. 2008-10-20 Fixed bug with bad variable name... Thanks Thomas!
  8. 2008-03-02 Added licensing terms under the MIT License
  9. Only remove unprocessable HTML tags if they exist in the array
  10. 2009-06-03 Normalize existing CSS (style) attributes in the HTML before we process the CSS.
  11. Made it so that the display:none stripper doesn't require a trailing semi-colon.
  12. 2009-08-13 Added support for subset class values (e.g. "p.class1.class2").
  13. Added better protection for bad css attributes.
  14. Fixed support for HTML entities.
  15. 2009-08-17 Fixed CSS selector processing so that selectors are processed by precedence/specificity, and not just in order.
  16. 2009-10-29 Fixed so that selectors appearing later in the CSS will have precedence over identical selectors appearing earlier.
  17. 2009-11-04 Explicitly declared static functions static to get rid of E_STRICT notices.
  18. 2010-05-18 Fixed bug where full url filenames with protocols wouldn't get split improperly when we explode on ':'... Thanks Mark!
  19. Added two new attribute selectors
  20. 2010-06-16 Added static caching for less processing overhead in situations where multiple emogrification takes place
  21. 2010-07-26 Fixed bug where '0' values were getting discarded because of php's empty() function... Thanks Scott!
  22. 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
  23. */
  24. class Emogrifier {
  25. private $html = '';
  26. private $css = '';
  27. private $unprocessableHTMLTags = array('wbr');
  28. public function __construct($html = '', $css = '') {
  29. $this->html = $html;
  30. $this->css = $css;
  31. }
  32. public function setHTML($html = '') { $this->html = $html; }
  33. public function setCSS($css = '') { $this->css = $css; }
  34. // there are some HTML tags that DOMDocument cannot process, and will throw an error if it encounters them.
  35. // these functions allow you to add/remove them if necessary.
  36. // it only strips them from the code (does not remove actual nodes).
  37. public function addUnprocessableHTMLTag($tag) { $this->unprocessableHTMLTags[] = $tag; }
  38. public function removeUnprocessableHTMLTag($tag) {
  39. if (($key = array_search($tag,$this->unprocessableHTMLTags)) !== false)
  40. unset($this->unprocessableHTMLTags[$key]);
  41. }
  42. // applies the CSS you submit to the html you submit. places the css inline
  43. public function emogrify() {
  44. $body = $this->html;
  45. // process the CSS here, turning the CSS style blocks into inline css
  46. if (count($this->unprocessableHTMLTags)) {
  47. $unprocessableHTMLTags = implode('|',$this->unprocessableHTMLTags);
  48. $body = preg_replace("/<($unprocessableHTMLTags)[^>]*>/i",'',$body);
  49. }
  50. //$encoding = mb_detect_encoding($body);
  51. $encoding = 'UTF-8';
  52. $body = mb_convert_encoding($body, 'HTML-ENTITIES', $encoding);
  53. $xmldoc =@ new DOMDocument;
  54. if(!is_object($xmldoc) || !method_exists($xmldoc,'loadHTML')) return $this->html;
  55. $xmldoc->encoding = $encoding;
  56. $xmldoc->strictErrorChecking = false;
  57. $xmldoc->formatOutput = true;
  58. //ACYBA MODIFICATION : let's avoid some warnings
  59. @$xmldoc->loadHTML($body);
  60. $xmldoc->normalizeDocument();
  61. $xpath = new DOMXPath($xmldoc);
  62. // before be begin processing the CSS file, parse the document and normalize all existing CSS attributes (changes 'DISPLAY: none' to 'display: none');
  63. // we wouldn't have to do this if DOMXPath supported XPath 2.0.
  64. $nodes = @$xpath->query('//*[@style]');
  65. if ($nodes->length > 0) foreach ($nodes as $node) $node->setAttribute('style',preg_replace('/[A-z\-]+(?=\:)/Se',"strtolower('\\0')",$node->getAttribute('style')));
  66. // get rid of css comment code
  67. $re_commentCSS = '/\/\*.*\*\//sU';
  68. $css = preg_replace($re_commentCSS,'',$this->css);
  69. static $csscache = array();
  70. $csskey = md5($css);
  71. if (!isset($csscache[$csskey])) {
  72. // process the CSS file for selectors and definitions
  73. $re_CSS = '/^\s*([^{]+){([^}]+)}/mis';
  74. preg_match_all($re_CSS,$css,$matches);
  75. $all_selectors = array();
  76. foreach ($matches[1] as $key => $selectorString) {
  77. // if there is a blank definition, skip
  78. if (!strlen(trim($matches[2][$key]))) continue;
  79. // else split by commas and duplicate attributes so we can sort by selector precedence
  80. $selectors = explode(',',$selectorString);
  81. foreach ($selectors as $selector) {
  82. // don't process pseudo-classes
  83. if (strpos($selector,':') !== false) continue;
  84. $all_selectors[] = array('selector' => $selector,
  85. 'attributes' => $matches[2][$key],
  86. 'index' => $key, // keep track of where it appears in the file, since order is important
  87. );
  88. }
  89. }
  90. // now sort the selectors by precedence
  91. usort($all_selectors, array('self','sortBySelectorPrecedence'));
  92. $csscache[$csskey] = $all_selectors;
  93. }
  94. foreach ($csscache[$csskey] as $value) {
  95. // query the body for the xpath selector
  96. $nodes = @$xpath->query($this->translateCSStoXpath(trim($value['selector'])));
  97. if(empty($nodes)) continue;
  98. foreach($nodes as $node) {
  99. // if it has a style attribute, get it, process it, and append (overwrite) new stuff
  100. if ($node->hasAttribute('style')) {
  101. // break it up into an associative array
  102. $oldStyleArr = $this->cssStyleDefinitionToArray($node->getAttribute('style'));
  103. $newStyleArr = $this->cssStyleDefinitionToArray($value['attributes']);
  104. // new styles overwrite the old styles (not technically accurate, but close enough)
  105. $combinedArr = array_merge($oldStyleArr,$newStyleArr);
  106. $style = '';
  107. foreach ($combinedArr as $k => $v) $style .= (strtolower($k) . ':' . $v . ';');
  108. } else {
  109. // otherwise create a new style
  110. $style = trim($value['attributes']);
  111. }
  112. $node->setAttribute('style',$style);
  113. }
  114. }
  115. // This removes styles from your email that contain display:none. You could comment these out if you want.
  116. $nodes = $xpath->query('//*[contains(translate(@style," ",""),"display:none")]');
  117. // the checks on parentNode and is_callable below are there to ensure that if we've deleted the parent node,
  118. // we don't try to call removeChild on a nonexistent child node
  119. if ($nodes->length > 0) foreach ($nodes as $node) if ($node->parentNode && is_callable(array($node->parentNode,'removeChild'))) $node->parentNode->removeChild($node);
  120. return $this->fixCompatibility($xmldoc->saveHTML());
  121. }
  122. private static function sortBySelectorPrecedence($a, $b) {
  123. $precedenceA = self::getCSSSelectorPrecedence($a['selector']);
  124. $precedenceB = self::getCSSSelectorPrecedence($b['selector']);
  125. // we want these sorted ascendingly so selectors with lesser precedence get processed first and
  126. // selectors with greater precedence get sorted last
  127. return ($precedenceA == $precedenceB) ? ($a['index'] < $b['index'] ? -1 : 1) : ($precedenceA < $precedenceB ? -1 : 1);
  128. }
  129. private static function getCSSSelectorPrecedence($selector) {
  130. static $selectorcache = array();
  131. $selectorkey = md5($selector);
  132. if (!isset($selectorcache[$selectorkey])) {
  133. $precedence = 0;
  134. $value = 100;
  135. $search = array('\#','\.',''); // ids: worth 100, classes: worth 10, elements: worth 1
  136. foreach ($search as $s) {
  137. if (trim($selector == '')) break;
  138. $num = 0;
  139. $selector = preg_replace('/'.$s.'\w+/','',$selector,-1,$num);
  140. $precedence += ($value * $num);
  141. $value /= 10;
  142. }
  143. $selectorcache[$selectorkey] = $precedence;
  144. }
  145. return $selectorcache[$selectorkey];
  146. }
  147. // right now we support all CSS 1 selectors and /some/ CSS2/3 selectors.
  148. // http://plasmasturm.org/log/444/
  149. private function translateCSStoXpath($css_selector) {
  150. $css_selector = trim($css_selector);
  151. static $xpathcache = array();
  152. $xpathkey = md5($css_selector);
  153. if (!isset($xpathcache[$xpathkey])) {
  154. // returns an Xpath selector
  155. $search = array(
  156. '/\s+>\s+/', // Matches any F element that is a child of an element E.
  157. '/(\w+)\s+\+\s+(\w+)/', // Matches any F element that is a child of an element E.
  158. '/\s+/', // Matches any F element that is a descendant of an E element.
  159. '/(\w)\[(\w+)\]/', // Matches element with attribute
  160. '/(\w)\[(\w+)\=[\'"]?(\w+)[\'"]?\]/', // Matches element with EXACT attribute
  161. '/(\w+)?\#([\w\-]+)/e', // Matches id attributes
  162. '/(\w+|\*)?((\.[\w\-]+)+)/e', // Matches class attributes
  163. );
  164. $replace = array(
  165. '/',
  166. '\\1/following-sibling::*[1]/self::\\2',
  167. '//',
  168. '\\1[@\\2]',
  169. '\\1[@\\2="\\3"]',
  170. "(strlen('\\1') ? '\\1' : '*').'[@id=\"\\2\"]'",
  171. "(strlen('\\1') ? '\\1' : '*').'[contains(concat(\" \",@class,\" \"),concat(\" \",\"'.implode('\",\" \"))][contains(concat(\" \",@class,\" \"),concat(\" \",\"',explode('.',substr('\\2',1))).'\",\" \"))]'",
  172. );
  173. $xpathcache[$xpathkey] = '//'.preg_replace($search,$replace,$css_selector);
  174. }
  175. return $xpathcache[$xpathkey];
  176. }
  177. private function cssStyleDefinitionToArray($style) {
  178. $definitions = explode(';',$style);
  179. $retArr = array();
  180. foreach ($definitions as $def) {
  181. if (empty($def) || strpos($def, ':') === false) continue;
  182. list($key,$value) = explode(':',$def,2);
  183. if (empty($key) || strlen(trim($value)) === 0) continue;
  184. $retArr[trim($key)] = trim($value);
  185. }
  186. return $retArr;
  187. }
  188. private function fixCompatibility($text){
  189. $replace = array();
  190. $replace['#<br>#i'] = '<br />';
  191. return preg_replace(array_keys($replace),$replace,$text);
  192. }
  193. }