InlineCssLib.php 7.8 KB

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