Number.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Validates a number as defined by the CSS spec.
  4. */
  5. class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
  6. {
  7. /**
  8. * Bool indicating whether or not only positive values allowed.
  9. */
  10. protected $non_negative = false;
  11. /**
  12. * @param $non_negative Bool indicating whether negatives are forbidden
  13. */
  14. public function __construct($non_negative = false) {
  15. $this->non_negative = $non_negative;
  16. }
  17. /**
  18. * @warning Some contexts do not pass $config, $context. These
  19. * variables should not be used without checking HTMLPurifier_Length
  20. */
  21. public function validate($number, $config, $context) {
  22. $number = $this->parseCDATA($number);
  23. if ($number === '') return false;
  24. if ($number === '0') return '0';
  25. $sign = '';
  26. switch ($number[0]) {
  27. case '-':
  28. if ($this->non_negative) return false;
  29. $sign = '-';
  30. case '+':
  31. $number = substr($number, 1);
  32. }
  33. if (ctype_digit($number)) {
  34. $number = ltrim($number, '0');
  35. return $number ? $sign . $number : '0';
  36. }
  37. // Period is the only non-numeric character allowed
  38. if (strpos($number, '.') === false) return false;
  39. list($left, $right) = explode('.', $number, 2);
  40. if ($left === '' && $right === '') return false;
  41. if ($left !== '' && !ctype_digit($left)) return false;
  42. $left = ltrim($left, '0');
  43. $right = rtrim($right, '0');
  44. if ($right === '') {
  45. return $left ? $sign . $left : '0';
  46. } elseif (!ctype_digit($right)) {
  47. return false;
  48. }
  49. return $sign . $left . '.' . $right;
  50. }
  51. }
  52. // vim: et sw=4 sts=4