PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/htmlpurifier/HTMLPurifier/Filter/ExtractStyleBlocks.php

https://github.com/mackensen/moodle
PHP | 341 lines | 185 code | 13 blank | 143 comment | 37 complexity | 10585ebecdd3eb0bee992b156bed0463 MD5 | raw file
  1. <?php
  2. // why is this a top level function? Because PHP 5.2.0 doesn't seem to
  3. // understand how to interpret this filter if it's a static method.
  4. // It's all really silly, but if we go this route it might be reasonable
  5. // to coalesce all of these methods into one.
  6. function htmlpurifier_filter_extractstyleblocks_muteerrorhandler()
  7. {
  8. }
  9. /**
  10. * This filter extracts <style> blocks from input HTML, cleans them up
  11. * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')
  12. * so they can be used elsewhere in the document.
  13. *
  14. * @note
  15. * See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for
  16. * sample usage.
  17. *
  18. * @note
  19. * This filter can also be used on stylesheets not included in the
  20. * document--something purists would probably prefer. Just directly
  21. * call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS()
  22. */
  23. class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter
  24. {
  25. /**
  26. * @type string
  27. */
  28. public $name = 'ExtractStyleBlocks';
  29. /**
  30. * @type array
  31. */
  32. private $_styleMatches = array();
  33. /**
  34. * @type csstidy
  35. */
  36. private $_tidy;
  37. /**
  38. * @type HTMLPurifier_AttrDef_HTML_ID
  39. */
  40. private $_id_attrdef;
  41. /**
  42. * @type HTMLPurifier_AttrDef_CSS_Ident
  43. */
  44. private $_class_attrdef;
  45. /**
  46. * @type HTMLPurifier_AttrDef_Enum
  47. */
  48. private $_enum_attrdef;
  49. public function __construct()
  50. {
  51. $this->_tidy = new csstidy();
  52. $this->_tidy->set_cfg('lowercase_s', false);
  53. $this->_id_attrdef = new HTMLPurifier_AttrDef_HTML_ID(true);
  54. $this->_class_attrdef = new HTMLPurifier_AttrDef_CSS_Ident();
  55. $this->_enum_attrdef = new HTMLPurifier_AttrDef_Enum(
  56. array(
  57. 'first-child',
  58. 'link',
  59. 'visited',
  60. 'active',
  61. 'hover',
  62. 'focus'
  63. )
  64. );
  65. }
  66. /**
  67. * Save the contents of CSS blocks to style matches
  68. * @param array $matches preg_replace style $matches array
  69. */
  70. protected function styleCallback($matches)
  71. {
  72. $this->_styleMatches[] = $matches[1];
  73. }
  74. /**
  75. * Removes inline <style> tags from HTML, saves them for later use
  76. * @param string $html
  77. * @param HTMLPurifier_Config $config
  78. * @param HTMLPurifier_Context $context
  79. * @return string
  80. * @todo Extend to indicate non-text/css style blocks
  81. */
  82. public function preFilter($html, $config, $context)
  83. {
  84. $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');
  85. if ($tidy !== null) {
  86. $this->_tidy = $tidy;
  87. }
  88. // NB: this must be NON-greedy because if we have
  89. // <style>foo</style> <style>bar</style>
  90. // we must not grab foo</style> <style>bar
  91. $html = preg_replace_callback('#<style(?:\s.*)?>(.*)<\/style>#isU', array($this, 'styleCallback'), $html);
  92. $style_blocks = $this->_styleMatches;
  93. $this->_styleMatches = array(); // reset
  94. $context->register('StyleBlocks', $style_blocks); // $context must not be reused
  95. if ($this->_tidy) {
  96. foreach ($style_blocks as &$style) {
  97. $style = $this->cleanCSS($style, $config, $context);
  98. }
  99. }
  100. return $html;
  101. }
  102. /**
  103. * Takes CSS (the stuff found in <style>) and cleans it.
  104. * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>
  105. * @param string $css CSS styling to clean
  106. * @param HTMLPurifier_Config $config
  107. * @param HTMLPurifier_Context $context
  108. * @throws HTMLPurifier_Exception
  109. * @return string Cleaned CSS
  110. */
  111. public function cleanCSS($css, $config, $context)
  112. {
  113. // prepare scope
  114. $scope = $config->get('Filter.ExtractStyleBlocks.Scope');
  115. if ($scope !== null) {
  116. $scopes = array_map('trim', explode(',', $scope));
  117. } else {
  118. $scopes = array();
  119. }
  120. // remove comments from CSS
  121. $css = trim($css);
  122. if (strncmp('<!--', $css, 4) === 0) {
  123. $css = substr($css, 4);
  124. }
  125. if (strlen($css) > 3 && substr($css, -3) == '-->') {
  126. $css = substr($css, 0, -3);
  127. }
  128. $css = trim($css);
  129. set_error_handler('htmlpurifier_filter_extractstyleblocks_muteerrorhandler');
  130. $this->_tidy->parse($css);
  131. restore_error_handler();
  132. $css_definition = $config->getDefinition('CSS');
  133. $html_definition = $config->getDefinition('HTML');
  134. $new_css = array();
  135. foreach ($this->_tidy->css as $k => $decls) {
  136. // $decls are all CSS declarations inside an @ selector
  137. $new_decls = array();
  138. foreach ($decls as $selector => $style) {
  139. $selector = trim($selector);
  140. if ($selector === '') {
  141. continue;
  142. } // should not happen
  143. // Parse the selector
  144. // Here is the relevant part of the CSS grammar:
  145. //
  146. // ruleset
  147. // : selector [ ',' S* selector ]* '{' ...
  148. // selector
  149. // : simple_selector [ combinator selector | S+ [ combinator? selector ]? ]?
  150. // combinator
  151. // : '+' S*
  152. // : '>' S*
  153. // simple_selector
  154. // : element_name [ HASH | class | attrib | pseudo ]*
  155. // | [ HASH | class | attrib | pseudo ]+
  156. // element_name
  157. // : IDENT | '*'
  158. // ;
  159. // class
  160. // : '.' IDENT
  161. // ;
  162. // attrib
  163. // : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
  164. // [ IDENT | STRING ] S* ]? ']'
  165. // ;
  166. // pseudo
  167. // : ':' [ IDENT | FUNCTION S* [IDENT S*]? ')' ]
  168. // ;
  169. //
  170. // For reference, here are the relevant tokens:
  171. //
  172. // HASH #{name}
  173. // IDENT {ident}
  174. // INCLUDES ==
  175. // DASHMATCH |=
  176. // STRING {string}
  177. // FUNCTION {ident}\(
  178. //
  179. // And the lexical scanner tokens
  180. //
  181. // name {nmchar}+
  182. // nmchar [_a-z0-9-]|{nonascii}|{escape}
  183. // nonascii [\240-\377]
  184. // escape {unicode}|\\[^\r\n\f0-9a-f]
  185. // unicode \\{h}}{1,6}(\r\n|[ \t\r\n\f])?
  186. // ident -?{nmstart}{nmchar*}
  187. // nmstart [_a-z]|{nonascii}|{escape}
  188. // string {string1}|{string2}
  189. // string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\"
  190. // string2 \'([^\n\r\f\\"]|\\{nl}|{escape})*\'
  191. //
  192. // We'll implement a subset (in order to reduce attack
  193. // surface); in particular:
  194. //
  195. // - No Unicode support
  196. // - No escapes support
  197. // - No string support (by proxy no attrib support)
  198. // - element_name is matched against allowed
  199. // elements (some people might find this
  200. // annoying...)
  201. // - Pseudo-elements one of :first-child, :link,
  202. // :visited, :active, :hover, :focus
  203. // handle ruleset
  204. $selectors = array_map('trim', explode(',', $selector));
  205. $new_selectors = array();
  206. foreach ($selectors as $sel) {
  207. // split on +, > and spaces
  208. $basic_selectors = preg_split('/\s*([+> ])\s*/', $sel, -1, PREG_SPLIT_DELIM_CAPTURE);
  209. // even indices are chunks, odd indices are
  210. // delimiters
  211. $nsel = null;
  212. $delim = null; // guaranteed to be non-null after
  213. // two loop iterations
  214. for ($i = 0, $c = count($basic_selectors); $i < $c; $i++) {
  215. $x = $basic_selectors[$i];
  216. if ($i % 2) {
  217. // delimiter
  218. if ($x === ' ') {
  219. $delim = ' ';
  220. } else {
  221. $delim = ' ' . $x . ' ';
  222. }
  223. } else {
  224. // simple selector
  225. $components = preg_split('/([#.:])/', $x, -1, PREG_SPLIT_DELIM_CAPTURE);
  226. $sdelim = null;
  227. $nx = null;
  228. for ($j = 0, $cc = count($components); $j < $cc; $j++) {
  229. $y = $components[$j];
  230. if ($j === 0) {
  231. if ($y === '*' || isset($html_definition->info[$y = strtolower($y)])) {
  232. $nx = $y;
  233. } else {
  234. // $nx stays null; this matters
  235. // if we don't manage to find
  236. // any valid selector content,
  237. // in which case we ignore the
  238. // outer $delim
  239. }
  240. } elseif ($j % 2) {
  241. // set delimiter
  242. $sdelim = $y;
  243. } else {
  244. $attrdef = null;
  245. if ($sdelim === '#') {
  246. $attrdef = $this->_id_attrdef;
  247. } elseif ($sdelim === '.') {
  248. $attrdef = $this->_class_attrdef;
  249. } elseif ($sdelim === ':') {
  250. $attrdef = $this->_enum_attrdef;
  251. } else {
  252. throw new HTMLPurifier_Exception('broken invariant sdelim and preg_split');
  253. }
  254. $r = $attrdef->validate($y, $config, $context);
  255. if ($r !== false) {
  256. if ($r !== true) {
  257. $y = $r;
  258. }
  259. if ($nx === null) {
  260. $nx = '';
  261. }
  262. $nx .= $sdelim . $y;
  263. }
  264. }
  265. }
  266. if ($nx !== null) {
  267. if ($nsel === null) {
  268. $nsel = $nx;
  269. } else {
  270. $nsel .= $delim . $nx;
  271. }
  272. } else {
  273. // delimiters to the left of invalid
  274. // basic selector ignored
  275. }
  276. }
  277. }
  278. if ($nsel !== null) {
  279. if (!empty($scopes)) {
  280. foreach ($scopes as $s) {
  281. $new_selectors[] = "$s $nsel";
  282. }
  283. } else {
  284. $new_selectors[] = $nsel;
  285. }
  286. }
  287. }
  288. if (empty($new_selectors)) {
  289. continue;
  290. }
  291. $selector = implode(', ', $new_selectors);
  292. foreach ($style as $name => $value) {
  293. if (!isset($css_definition->info[$name])) {
  294. unset($style[$name]);
  295. continue;
  296. }
  297. $def = $css_definition->info[$name];
  298. $ret = $def->validate($value, $config, $context);
  299. if ($ret === false) {
  300. unset($style[$name]);
  301. } else {
  302. $style[$name] = $ret;
  303. }
  304. }
  305. $new_decls[$selector] = $style;
  306. }
  307. $new_css[$k] = $new_decls;
  308. }
  309. // remove stuff that shouldn't be used, could be reenabled
  310. // after security risks are analyzed
  311. $this->_tidy->css = $new_css;
  312. $this->_tidy->import = array();
  313. $this->_tidy->charset = null;
  314. $this->_tidy->namespace = null;
  315. $css = $this->_tidy->print->plain();
  316. // we are going to escape any special characters <>& to ensure
  317. // that no funny business occurs (i.e. </style> in a font-family prop).
  318. if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {
  319. $css = str_replace(
  320. array('<', '>', '&'),
  321. array('\3C ', '\3E ', '\26 '),
  322. $css
  323. );
  324. }
  325. return $css;
  326. }
  327. }
  328. // vim: et sw=4 sts=4