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. */
  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. 'correctUtf8' => 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. */
  39. public function process($html, $css = null) {
  40. if (($html = trim($html)) === '') {
  41. return $html;
  42. }
  43. $method = '_process' . ucfirst($this->settings['engine']);
  44. return $this->{$method}($html, $css);
  45. }
  46. /**
  47. * @return string Result
  48. */
  49. protected function _processEmogrifier($html, $css) {
  50. $css .= $this->_extractAndRemoveCss($html);
  51. App::import('Vendor', 'Emogrifier', array('file' => 'emogrifier' . DS . 'emogrifier.php'));
  52. $Emogrifier = new Emogrifier($html, $css);
  53. return @$Emogrifier->emogrify();
  54. }
  55. /**
  56. * Process css blocks to inline css
  57. * Also works for html snippets (without <html>)
  58. *
  59. * @return string HTML output
  60. */
  61. protected function _processCssToInline($html, $css) {
  62. App::import('Vendor', 'Tools.CssToInlineStyles', array('file' => 'CssToInlineStyles' . DS . 'CssToInlineStyles.php'));
  63. //fix issue with <html> being added
  64. $separator = '~~~~~~~~~~~~~~~~~~~~';
  65. if (strpos($html, '<html') === false) {
  66. $incomplete = true;
  67. $html = $separator . $html . $separator;
  68. }
  69. $CssToInlineStyles = new CssToInlineStyles($html, $css);
  70. if ($this->settings['cleanup']) {
  71. $CssToInlineStyles->setCleanup();
  72. }
  73. if ($this->settings['useInlineStylesBlock']) {
  74. $CssToInlineStyles->setUseInlineStylesBlock();
  75. }
  76. if ($this->settings['removeCss']) {
  77. $CssToInlineStyles->setStripOriginalStyleTags();
  78. }
  79. if ($this->settings['correctUtf8']) {
  80. $CssToInlineStyles->setCorrectUtf8();
  81. }
  82. if ($this->settings['debug']) {
  83. CakeLog::write('css', $html);
  84. }
  85. $html = $CssToInlineStyles->convert($this->settings['xhtmlOutput']);
  86. if ($this->settings['removeCss']) {
  87. //$html = preg_replace('/\<style(.*)\>(.*)\<\/style\>/i', '', $html);
  88. $html = $this->stripOnly($html, array('style', 'script'), true);
  89. //CakeLog::write('css', $html);
  90. }
  91. if (!empty($incomplete)) {
  92. $html = substr($html, strpos($html, $separator) + 20);
  93. $html = substr($html, 0, strpos($html, $separator));
  94. $html = trim($html);
  95. }
  96. return $html;
  97. }
  98. /**
  99. * Some reverse function of strip_tags with blacklisting instead of whitelisting
  100. * //maybe move to Tools.Utility/String/Text?
  101. *
  102. * @return string cleanedStr
  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. $removeDoms = 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->mediaTypes as $cssLinkMedia) {
  139. if (strstr($link->getAttribute('media'), $cssLinkMedia)) {
  140. $css .= $this->_findAndLoadCssFile($link->getAttribute('href')) . "\n\n";
  141. $removeDoms[] = $link;
  142. }
  143. }
  144. } else {
  145. $css .= $this->_findAndLoadCssFile($link->getAttribute('href')) . "\n\n";
  146. $removeDoms[] = $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->mediaTypes as $cssLinkMedia) {
  156. if (strstr($style->getAttribute('media'), $cssLinkMedia)) {
  157. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  158. $removeDoms[] = $style;
  159. }
  160. }
  161. } else {
  162. $css .= $this->_parseInlineCssAndLoadImports($style->nodeValue);
  163. $removeDoms[] = $style;
  164. }
  165. }
  166. // Remove
  167. if ($this->settings['removeCss']) {
  168. foreach ($removeDoms as $removeDom) {
  169. try {
  170. $removeDom->parentNode->removeChild($removeDom);
  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. $cssFilenames = 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. $cssHrefPaths = array();
  188. for ($i = count($cssHrefs) - 1; $i > 0; $i--) {
  189. if (isset($cssHrefPaths[count($cssHrefPaths) - 1])) {
  190. $cssHrefPaths[] = $cssHrefs[$i] . DS . $cssHrefPaths[count($cssHrefPaths) - 1];
  191. } else {
  192. $cssHrefPaths[] = $cssHrefs[$i];
  193. }
  194. }
  195. // the longest string match will be the match we are looking for
  196. $bestCssFilename = null;
  197. $bestCssMatchLength = 0;
  198. foreach ($cssFilenames as $cssFilename) {
  199. foreach ($cssHrefPaths as $cssHrefPath) {
  200. $regex = '/' . str_replace('/', '\/', str_replace('.', '\.', $cssHrefPath)) . '/';
  201. if (preg_match($regex, $cssFilename, $match)) {
  202. if (strlen($match[0]) > $bestCssMatchLength) {
  203. $bestCssMatchLength = strlen($match[0]);
  204. $bestCssFilename = $cssFilename;
  205. }
  206. }
  207. }
  208. }
  209. $css = null;
  210. if (!empty($bestCssFilename) && is_file($bestCssFilename)) {
  211. $css = file_get_contents($bestCssFilename);
  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->importExternalCss) {
  247. $css .= file_get_contents($url);
  248. }
  249. } else {
  250. $css .= $this->_findAndLoadCssFile($url);
  251. }
  252. }
  253. }
  254. return $css;
  255. }
  256. }