InlineCssLib.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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) === '') {
  109. array_pop($tags);
  110. }
  111. }
  112. foreach ($tags as $tag) {
  113. if ($stripContent) {
  114. $content = '(.+</' . $tag . '[^>]*>|)';
  115. }
  116. $str = preg_replace('#</?' . $tag . '[^>]*>' . $content . '#is', '', $str);
  117. }
  118. return $str;
  119. }
  120. /**
  121. * _extractAndRemoveCss - extracts any CSS from the rendered view and
  122. * removes it from the $html
  123. *
  124. * @return string
  125. */
  126. protected function _extractAndRemoveCss($html) {
  127. $css = null;
  128. $DOM = new DOMDocument;
  129. $DOM->loadHTML($html);
  130. // DOM removal queue
  131. $remove_doms = array();
  132. // catch <link> style sheet content
  133. $links = $DOM->getElementsByTagName('link');
  134. foreach ($links as $link) {
  135. if ($link->hasAttribute('href') && preg_match("/\.css$/i", $link->getAttribute('href'))) {
  136. // find the css file and load contents
  137. if ($link->hasAttribute('media')) {
  138. foreach ($this->media_types as $css_link_media) {
  139. if (strstr($link->getAttribute('media'), $css_link_media)) {
  140. $css .= $this->_findAndLoadCssFile($link->getAttribute('href')) . "\n\n";
  141. $remove_doms[] = $link;
  142. }
  143. }
  144. } else {
  145. $css .= $this->_findAndLoadCssFile($link->getAttribute('href')) . "\n\n";
  146. $remove_doms[] = $link;
  147. }
  148. }
  149. }
  150. // Catch embeded <style> and @import CSS content
  151. $styles = $DOM->getElementsByTagName('style');
  152. // Style
  153. foreach ($styles as $style) {
  154. if ($style->hasAttribute('media')) {
  155. foreach ($this->media_types as $css_link_media) {
  156. if (strstr($style->getAttribute('media'), $css_link_media)) {
  157. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  158. $remove_doms[] = $style;
  159. }
  160. }
  161. } else {
  162. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  163. $remove_doms[] = $style;
  164. }
  165. }
  166. // Remove
  167. if ($this->settings['removeCss']) {
  168. foreach ($remove_doms as $remove_dom) {
  169. try {
  170. $remove_dom->parentNode->removeChild($remove_dom);
  171. } catch (DOMException $e) {}
  172. }
  173. $html = $DOM->saveHTML();
  174. }
  175. return $html;
  176. }
  177. /**
  178. * _findAndLoadCssFile - finds the appropriate css file within the CSS path
  179. *
  180. * @param string $cssHref
  181. * @return string Content
  182. */
  183. protected function _findAndLoadCssFile($cssHref) {
  184. $css_filenames = array_merge($this->_globRecursive(CSS.'*.Css'), $this->_globRecursive(CSS.'*.CSS'), $this->_globRecursive(CSS.'*.css'));
  185. // Build an array of the ever more path specific $cssHref location
  186. $cssHrefs = split(DS, $cssHref);
  187. $cssHref_paths = array();
  188. for ($i = count($cssHrefs) - 1; $i > 0; $i--) {
  189. if (isset($cssHref_paths[count($cssHref_paths) - 1])) {
  190. $cssHref_paths[] = $cssHrefs[$i] . DS . $cssHref_paths[count($cssHref_paths) - 1];
  191. } else {
  192. $cssHref_paths[] = $cssHrefs[$i];
  193. }
  194. }
  195. // the longest string match will be the match we are looking for
  196. $best_css_filename = null;
  197. $best_css_match_length = 0;
  198. foreach ($css_filenames as $css_filename) {
  199. foreach ($cssHref_paths as $cssHref_path) {
  200. $regex = '/' . str_replace('/', '\/', str_replace('.', '\.', $cssHref_path)) . '/';
  201. if (preg_match($regex, $css_filename, $match)) {
  202. if (strlen($match[0]) > $best_css_match_length) {
  203. $best_css_match_length = strlen($match[0]);
  204. $best_css_filename = $css_filename;
  205. }
  206. }
  207. }
  208. }
  209. $css = null;
  210. if (!empty($best_css_filename) && is_file($best_css_filename)) {
  211. $css = file_get_contents($best_css_filename);
  212. }
  213. return $css;
  214. }
  215. /**
  216. * _globRecursive
  217. *
  218. * @param string $pattern
  219. * @param integer $flags
  220. * @return array
  221. */
  222. protected function _globRecursive($pattern, $flags = 0) {
  223. $files = glob($pattern, $flags);
  224. foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
  225. $files = array_merge($files, $this->_globRecursive($dir . '/' . basename($pattern), $flags));
  226. }
  227. return $files;
  228. }
  229. /**
  230. * _parseInlineCssAndLoadImports
  231. *
  232. * @param string Input
  233. * @return string Result
  234. */
  235. protected function _parseInlineCssAndLoadImports($css) {
  236. // Remove any <!-- --> comment tags - they are valid in HTML but we probably
  237. // don't want to be commenting out CSS
  238. $css = str_replace('-->', '', str_replace('<!--', '', $css)) . "\n\n";
  239. // Load up the @import CSS if any exists
  240. preg_match_all("/\@import.*?url\((.*?)\)/i", $css, $matches);
  241. if (isset($matches[1]) && is_array($matches[1])) {
  242. // First remove the @imports
  243. $css = preg_replace("/\@import.*?url\(.*?\).*?;/i", '', $css);
  244. foreach ($matches[1] as $url) {
  245. if (preg_match("/^http/i", $url)) {
  246. if ($this->import_external_css) {
  247. $css .= file_get_contents($url);
  248. }
  249. } else {
  250. $css .= $this->_findAndLoadCssFile($url);
  251. }
  252. }
  253. }
  254. return $css;
  255. }
  256. }