InlineCssLib.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. /**
  3. * Wrapper for Inline CSS replacement
  4. * Useful for sending HTML emails
  5. *
  6. * Note: requires vendors CssToInline or emogrifier!
  7. * Default engine: CssToInline
  8. *
  9. * @author Mark Scherer
  10. * @copyright Mark Scherer
  11. * @license MIT
  12. * 2012-02-19 ms
  13. */
  14. class InlineCssLib {
  15. const ENGINE_CSS_TO_INLINE = 'cssToInline';
  16. const ENGINE_EMOGRIFIER = 'emogrifier';
  17. protected $_defaults = array(
  18. 'engine' => self::ENGINE_CSS_TO_INLINE,
  19. 'cleanup' => true,
  20. 'useInlineStylesBlock' => true,
  21. 'xhtmlOutput' => false,
  22. 'removeCss' => true,
  23. 'debug' => false,
  24. );
  25. public $settings = array();
  26. /**
  27. * startup
  28. */
  29. public function __construct($settings = array()) {
  30. $defaults = am($this->_defaults, (array) Configure::read('InlineCss'));
  31. $this->settings = array_merge($defaults, $settings);
  32. if (!method_exists($this, '_process'.ucfirst($this->settings['engine']))) {
  33. throw new InternalErrorException('Engine does not exist');
  34. }
  35. }
  36. /**
  37. * @return string Result
  38. * 2012-01-29 ms
  39. */
  40. public function process($html, $css = null) {
  41. if (($html = trim($html)) === '') {
  42. return $html;
  43. }
  44. $method = '_process'.ucfirst($this->settings['engine']);
  45. return $this->{$method}($html, $css);
  46. }
  47. /**
  48. * @return string Result
  49. * 2012-01-29 ms
  50. */
  51. protected function _processEmogrifier($html, $css) {
  52. $css .= $this->_extractAndRemoveCss($html);
  53. App::import('Vendor', 'Emogrifier', array('file' => 'emogrifier'.DS.'emogrifier.php'));
  54. $Emogrifier = new Emogrifier($html, $css);
  55. return @$Emogrifier->emogrify();
  56. }
  57. /**
  58. * Process css blocks to inline css
  59. * Also works for html snippets (without <html>)
  60. *
  61. * @return string HTML output
  62. */
  63. protected function _processCssToInline($html, $css) {
  64. App::import('Vendor', 'CssToInline', array('file' => 'css_to_inline_styles'.DS.'css_to_inline_styles.php'));
  65. //fix issue with <html> being added
  66. $separator = '~~~~~~~~~~~~~~~~~~~~';
  67. if (strpos($html, '<html>') === false) {
  68. $incomplete = true;
  69. $html = $separator . $html . $separator;
  70. }
  71. $CssToInlineStyles = new CSSToInlineStyles($html, $css);
  72. if ($this->settings['cleanup']) {
  73. $CssToInlineStyles->setCleanup();
  74. }
  75. if ($this->settings['useInlineStylesBlock']) {
  76. $CssToInlineStyles->setUseInlineStylesBlock();
  77. }
  78. if ($this->settings['removeCss']) {
  79. $CssToInlineStyles->setStripOriginalStyleTags();
  80. }
  81. if ($this->settings['debug']) {
  82. CakeLog::write('css', $html);
  83. }
  84. $html = $CssToInlineStyles->convert($this->settings['xhtmlOutput']);
  85. if ($this->settings['removeCss']) {
  86. //$html = preg_replace('/\<style(.*)\>(.*)\<\/style\>/i', '', $html);
  87. $html = $this->stripOnly($html, array('style', 'script'), true);
  88. //CakeLog::write('css', $html);
  89. }
  90. if (!empty($incomplete)) {
  91. $html = substr($html, strpos($html, $separator) + 20);
  92. $html = substr($html, 0, strpos($html, $separator));
  93. $html = trim($html);
  94. }
  95. return $html;
  96. }
  97. /**
  98. * some reverse function of strip_tags with blacklisting instead of whitelisting
  99. * //maybe move to Tools.Utility/String/Text?
  100. *
  101. * @return string $cleanedStr
  102. * 2012-01-29 ms
  103. */
  104. public function stripOnly($str, $tags, $stripContent = false) {
  105. $content = '';
  106. if(!is_array($tags)) {
  107. $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
  108. if(end($tags) == '') array_pop($tags);
  109. }
  110. foreach($tags as $tag) {
  111. if ($stripContent)
  112. $content = '(.+</'.$tag.'[^>]*>|)';
  113. $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
  114. }
  115. return $str;
  116. }
  117. /**
  118. * _extractAndRemoveCss - extracts any CSS from the rendered view and
  119. * removes it from the $html
  120. *
  121. * @return string
  122. */
  123. protected function _extractAndRemoveCss($html) {
  124. $css = null;
  125. $DOM = new DOMDocument;
  126. $DOM->loadHTML($html);
  127. // DOM removal queue
  128. $remove_doms = array();
  129. // catch <link> style sheet content
  130. $links = $DOM->getElementsByTagName('link');
  131. foreach($links as $link) {
  132. if ($link->hasAttribute('href') && preg_match("/\.css$/i", $link->getAttribute('href'))) {
  133. // find the css file and load contents
  134. if ($link->hasAttribute('media')) {
  135. foreach($this->media_types as $css_link_media) {
  136. if (strstr($link->getAttribute('media'), $css_link_media)) {
  137. $css .= $this->_findAndLoadCssFile($link->getAttribute('href'))."\n\n";
  138. $remove_doms[] = $link;
  139. }
  140. }
  141. } else {
  142. $css .= $this->_findAndLoadCssFile($link->getAttribute('href'))."\n\n";
  143. $remove_doms[] = $link;
  144. }
  145. }
  146. }
  147. // Catch embeded <style> and @import CSS content
  148. $styles = $DOM->getElementsByTagName('style');
  149. // Style
  150. foreach ($styles as $style) {
  151. if ($style->hasAttribute('media')) {
  152. foreach($this->media_types as $css_link_media) {
  153. if (strstr($style->getAttribute('media'), $css_link_media)) {
  154. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  155. $remove_doms[] = $style;
  156. }
  157. }
  158. } else {
  159. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  160. $remove_doms[] = $style;
  161. }
  162. }
  163. // Remove
  164. if ($this->settings['removeCss']) {
  165. foreach ($remove_doms as $remove_dom) {
  166. try {
  167. $remove_dom->parentNode->removeChild($remove_dom);
  168. } catch (DOMException $e) {}
  169. }
  170. $html = $DOM->saveHTML();
  171. }
  172. return $html;
  173. }
  174. /**
  175. * _findAndLoadCssFile - finds the appropriate css file within the CSS path
  176. *
  177. * @param string $cssHref
  178. * @return string Content
  179. */
  180. protected function _findAndLoadCssFile($cssHref) {
  181. $css_filenames = array_merge($this->_globRecursive(CSS.'*.Css'), $this->_globRecursive(CSS.'*.CSS'), $this->_globRecursive(CSS.'*.css'));
  182. // Build an array of the ever more path specific $cssHref location
  183. $cssHrefs = split(DS, $cssHref);
  184. $cssHref_paths = array();
  185. for($i=count($cssHrefs)-1; $i>0; $i--) {
  186. if(isset($cssHref_paths[count($cssHref_paths)-1])) {
  187. $cssHref_paths[] = $cssHrefs[$i].DS.$cssHref_paths[count($cssHref_paths)-1];
  188. }
  189. else {
  190. $cssHref_paths[] = $cssHrefs[$i];
  191. }
  192. }
  193. // the longest string match will be the match we are looking for
  194. $best_css_filename = null;
  195. $best_css_match_length = 0;
  196. foreach($css_filenames as $css_filename) {
  197. foreach($cssHref_paths as $cssHref_path) {
  198. $regex = "/".str_replace('/','\/', str_replace('.', '\.', $cssHref_path))."/";
  199. if(preg_match($regex, $css_filename, $match)) {
  200. if(strlen($match[0]) > $best_css_match_length) {
  201. $best_css_match_length = strlen($match[0]);
  202. $best_css_filename = $css_filename;
  203. }
  204. }
  205. }
  206. }
  207. $css = null;
  208. if(!empty($best_css_filename) && is_file($best_css_filename)) {
  209. $css = file_get_contents($best_css_filename);
  210. }
  211. return $css;
  212. }
  213. /**
  214. * _globRecursive
  215. *
  216. * @param string $pattern
  217. * @param int $flags
  218. * @return array
  219. */
  220. protected function _globRecursive($pattern, $flags = 0) {
  221. $files = glob($pattern, $flags);
  222. foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
  223. $files = array_merge($files, $this->_globRecursive($dir . '/' . basename($pattern), $flags));
  224. }
  225. return $files;
  226. }
  227. /**
  228. * _parseInlineCssAndLoadImports
  229. *
  230. * @param string Input
  231. * @return string Result
  232. */
  233. protected function _parseInlineCssAndLoadImports($css) {
  234. // Remove any <!-- --> comment tags - they are valid in HTML but we probably
  235. // don't want to be commenting out CSS
  236. $css = str_replace('-->', '', str_replace('<!--', '', $css))."\n\n";
  237. // Load up the @import CSS if any exists
  238. preg_match_all("/\@import.*?url\((.*?)\)/i", $css, $matches);
  239. if (isset($matches[1]) && is_array($matches[1])) {
  240. // First remove the @imports
  241. $css = preg_replace("/\@import.*?url\(.*?\).*?;/i", '', $css);
  242. foreach ($matches[1] as $url) {
  243. if (preg_match("/^http/i", $url)) {
  244. if ($this->import_external_css) {
  245. $css .= file_get_contents($url);
  246. }
  247. } else {
  248. $css .= $this->_findAndLoadCssFile($url);
  249. }
  250. }
  251. }
  252. return $css;
  253. }
  254. }