CSS.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Validates the HTML attribute style, otherwise known as CSS.
  4. * @note We don't implement the whole CSS specification, so it might be
  5. * difficult to reuse this component in the context of validating
  6. * actual stylesheet declarations.
  7. * @note If we were really serious about validating the CSS, we would
  8. * tokenize the styles and then parse the tokens. Obviously, we
  9. * are not doing that. Doing that could seriously harm performance,
  10. * but would make these components a lot more viable for a CSS
  11. * filtering solution.
  12. */
  13. class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
  14. {
  15. public function validate($css, $config, $context) {
  16. $css = $this->parseCDATA($css);
  17. $definition = $config->getCSSDefinition();
  18. // we're going to break the spec and explode by semicolons.
  19. // This is because semicolon rarely appears in escaped form
  20. // Doing this is generally flaky but fast
  21. // IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI
  22. // for details
  23. $declarations = explode(';', $css);
  24. $propvalues = array();
  25. /**
  26. * Name of the current CSS property being validated.
  27. */
  28. $property = false;
  29. $context->register('CurrentCSSProperty', $property);
  30. foreach ($declarations as $declaration) {
  31. if (!$declaration) continue;
  32. if (!strpos($declaration, ':')) continue;
  33. list($property, $value) = explode(':', $declaration, 2);
  34. $property = trim($property);
  35. $value = trim($value);
  36. $ok = false;
  37. do {
  38. if (isset($definition->info[$property])) {
  39. $ok = true;
  40. break;
  41. }
  42. if (ctype_lower($property)) break;
  43. $property = strtolower($property);
  44. if (isset($definition->info[$property])) {
  45. $ok = true;
  46. break;
  47. }
  48. } while(0);
  49. if (!$ok) continue;
  50. // inefficient call, since the validator will do this again
  51. if (strtolower(trim($value)) !== 'inherit') {
  52. // inherit works for everything (but only on the base property)
  53. $result = $definition->info[$property]->validate(
  54. $value, $config, $context );
  55. } else {
  56. $result = 'inherit';
  57. }
  58. if ($result === false) continue;
  59. $propvalues[$property] = $result;
  60. }
  61. $context->destroy('CurrentCSSProperty');
  62. // procedure does not write the new CSS simultaneously, so it's
  63. // slightly inefficient, but it's the only way of getting rid of
  64. // duplicates. Perhaps config to optimize it, but not now.
  65. $new_declarations = '';
  66. foreach ($propvalues as $prop => $value) {
  67. $new_declarations .= "$prop:$value;";
  68. }
  69. return $new_declarations ? $new_declarations : false;
  70. }
  71. }
  72. // vim: et sw=4 sts=4