InlineCssLib.php 8.7 KB

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