PageRenderTime 26ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Quản lý website bán mỹ phẩm PHP/components/com_acymailing/inc/emogrifier/emogrifier.php

https://gitlab.com/phamngsinh/baitaplon_sinhvien
PHP | 236 lines | 146 code | 34 blank | 56 comment | 24 complexity | eff8b2d20d58dc611df11ce5e8073eeb 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. for($a = count($csscache[$csskey]) -1;$a>=0;$a--) {
  95. // query the body for the xpath selector
  96. $nodes = @$xpath->query($this->translateCSStoXpath(trim($csscache[$csskey][$a]['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($csscache[$csskey][$a]['attributes']);
  104. // new styles overwrite the old styles (not technically accurate, but close enough)
  105. //Changed by Acyba, we don't overwrite the old styles, we keep them and add only the new ones
  106. //$combinedArr = array_merge($oldStyleArr,$newStyleArr);
  107. $combinedArr = array_merge($newStyleArr,$oldStyleArr);
  108. $style = '';
  109. foreach ($combinedArr as $k => $v) $style .= (strtolower($k) . ':' . $v . ';');
  110. } else {
  111. // otherwise create a new style
  112. $style = trim($csscache[$csskey][$a]['attributes']);
  113. }
  114. $node->setAttribute('style',$style);
  115. }
  116. }
  117. // This removes styles from your email that contain display:none. You could comment these out if you want.
  118. $nodes = $xpath->query('//*[contains(translate(@style," ",""),"display:none")]');
  119. // the checks on parentNode and is_callable below are there to ensure that if we've deleted the parent node,
  120. // we don't try to call removeChild on a nonexistent child node
  121. if ($nodes->length > 0) foreach ($nodes as $node) if ($node->parentNode && is_callable(array($node->parentNode,'removeChild'))) $node->parentNode->removeChild($node);
  122. return $this->fixCompatibility($xmldoc->saveHTML());
  123. }
  124. private static function sortBySelectorPrecedence($a, $b) {
  125. $precedenceA = self::getCSSSelectorPrecedence($a['selector']);
  126. $precedenceB = self::getCSSSelectorPrecedence($b['selector']);
  127. // we want these sorted ascendingly so selectors with lesser precedence get processed first and
  128. // selectors with greater precedence get sorted last
  129. return ($precedenceA == $precedenceB) ? ($a['index'] < $b['index'] ? -1 : 1) : ($precedenceA < $precedenceB ? -1 : 1);
  130. }
  131. private static function getCSSSelectorPrecedence($selector) {
  132. static $selectorcache = array();
  133. $selectorkey = md5($selector);
  134. if (!isset($selectorcache[$selectorkey])) {
  135. $precedence = 0;
  136. $value = 100;
  137. $search = array('\#','\.',''); // ids: worth 100, classes: worth 10, elements: worth 1
  138. foreach ($search as $s) {
  139. if (trim($selector == '')) break;
  140. $num = 0;
  141. $selector = preg_replace('/'.$s.'\w+/','',$selector,-1,$num);
  142. $precedence += ($value * $num);
  143. $value /= 10;
  144. }
  145. $selectorcache[$selectorkey] = $precedence;
  146. }
  147. return $selectorcache[$selectorkey];
  148. }
  149. // right now we support all CSS 1 selectors and /some/ CSS2/3 selectors.
  150. // http://plasmasturm.org/log/444/
  151. private function translateCSStoXpath($css_selector) {
  152. $css_selector = trim($css_selector);
  153. static $xpathcache = array();
  154. $xpathkey = md5($css_selector);
  155. if (!isset($xpathcache[$xpathkey])) {
  156. // returns an Xpath selector
  157. $search = array(
  158. '/\s+>\s+/', // Matches any F element that is a child of an element E.
  159. '/(\w+)\s+\+\s+(\w+)/', // Matches any F element that is a child of an element E.
  160. '/\s+/', // Matches any F element that is a descendant of an E element.
  161. '/(\w)\[(\w+)\]/', // Matches element with attribute
  162. '/(\w)\[(\w+)\=[\'"]?(\w+)[\'"]?\]/', // Matches element with EXACT attribute
  163. '/(\w+)?\#([\w\-]+)/e', // Matches id attributes
  164. '/(\w+|\*)?((\.[\w\-]+)+)/e', // Matches class attributes
  165. );
  166. $replace = array(
  167. '/',
  168. '\\1/following-sibling::*[1]/self::\\2',
  169. '//',
  170. '\\1[@\\2]',
  171. '\\1[@\\2="\\3"]',
  172. "(strlen('\\1') ? '\\1' : '*').'[@id=\"\\2\"]'",
  173. "(strlen('\\1') ? '\\1' : '*').'[contains(concat(\" \",@class,\" \"),concat(\" \",\"'.implode('\",\" \"))][contains(concat(\" \",@class,\" \"),concat(\" \",\"',explode('.',substr('\\2',1))).'\",\" \"))]'",
  174. );
  175. $xpathcache[$xpathkey] = '//'.preg_replace($search,$replace,$css_selector);
  176. }
  177. return $xpathcache[$xpathkey];
  178. }
  179. private function cssStyleDefinitionToArray($style) {
  180. $definitions = explode(';',$style);
  181. $retArr = array();
  182. foreach ($definitions as $def) {
  183. if (empty($def) || strpos($def, ':') === false) continue;
  184. list($key,$value) = explode(':',$def,2);
  185. if (empty($key) || strlen(trim($value)) === 0) continue;
  186. $retArr[trim($key)] = trim($value);
  187. }
  188. return $retArr;
  189. }
  190. private function fixCompatibility($text){
  191. $replace = array();
  192. $replace['#<br>#i'] = '<br />';
  193. //We replace the header properly as it may display a non valid DOCTYPE...
  194. $replace['#<\!DOCTYPE[^>]*>#Usi'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
  195. $body = preg_replace(array_keys($replace),$replace,$text);
  196. //Be careful with that line!
  197. //$body = mb_convert_encoding($body, 'UTF-8', 'HTML-ENTITIES');
  198. return $body;
  199. }
  200. }