InlineCssLib.php 8.8 KB

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