File indexing completed on 2024-12-22 05:36:18

0001 <?php
0002 
0003 /**
0004  * Validates a number as defined by the CSS spec.
0005  */
0006 class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
0007 {
0008 
0009     /**
0010      * Indicates whether or not only positive values are allowed.
0011      * @type bool
0012      */
0013     protected $non_negative = false;
0014 
0015     /**
0016      * @param bool $non_negative indicates whether negatives are forbidden
0017      */
0018     public function __construct($non_negative = false)
0019     {
0020         $this->non_negative = $non_negative;
0021     }
0022 
0023     /**
0024      * @param string $number
0025      * @param HTMLPurifier_Config $config
0026      * @param HTMLPurifier_Context $context
0027      * @return string|bool
0028      * @warning Some contexts do not pass $config, $context. These
0029      *          variables should not be used without checking HTMLPurifier_Length
0030      */
0031     public function validate($number, $config, $context)
0032     {
0033         $number = $this->parseCDATA($number);
0034 
0035         if ($number === '') {
0036             return false;
0037         }
0038         if ($number === '0') {
0039             return '0';
0040         }
0041 
0042         $sign = '';
0043         switch ($number[0]) {
0044             case '-':
0045                 if ($this->non_negative) {
0046                     return false;
0047                 }
0048                 $sign = '-';
0049             case '+':
0050                 $number = substr($number, 1);
0051         }
0052 
0053         if (ctype_digit($number)) {
0054             $number = ltrim($number, '0');
0055             return $number ? $sign . $number : '0';
0056         }
0057 
0058         // Period is the only non-numeric character allowed
0059         if (strpos($number, '.') === false) {
0060             return false;
0061         }
0062 
0063         list($left, $right) = explode('.', $number, 2);
0064 
0065         if ($left === '' && $right === '') {
0066             return false;
0067         }
0068         if ($left !== '' && !ctype_digit($left)) {
0069             return false;
0070         }
0071 
0072         $left = ltrim($left, '0');
0073         $right = rtrim($right, '0');
0074 
0075         if ($right === '') {
0076             return $left ? $sign . $left : '0';
0077         } elseif (!ctype_digit($right)) {
0078             return false;
0079         }
0080         return $sign . $left . '.' . $right;
0081     }
0082 }
0083 
0084 // vim: et sw=4 sts=4