InlineCssLib.php 8.7 KB

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