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

0001 <?php
0002 
0003 /**
0004  * Class for converting between different unit-lengths as specified by
0005  * CSS.
0006  */
0007 class HTMLPurifier_UnitConverter
0008 {
0009 
0010     const ENGLISH = 1;
0011     const METRIC = 2;
0012     const DIGITAL = 3;
0013 
0014     /**
0015      * Units information array. Units are grouped into measuring systems
0016      * (English, Metric), and are assigned an integer representing
0017      * the conversion factor between that unit and the smallest unit in
0018      * the system. Numeric indexes are actually magical constants that
0019      * encode conversion data from one system to the next, with a O(n^2)
0020      * constraint on memory (this is generally not a problem, since
0021      * the number of measuring systems is small.)
0022      */
0023     protected static $units = array(
0024         self::ENGLISH => array(
0025             'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary
0026             'pt' => 4,
0027             'pc' => 48,
0028             'in' => 288,
0029             self::METRIC => array('pt', '0.352777778', 'mm'),
0030         ),
0031         self::METRIC => array(
0032             'mm' => 1,
0033             'cm' => 10,
0034             self::ENGLISH => array('mm', '2.83464567', 'pt'),
0035         ),
0036     );
0037 
0038     /**
0039      * Minimum bcmath precision for output.
0040      * @type int
0041      */
0042     protected $outputPrecision;
0043 
0044     /**
0045      * Bcmath precision for internal calculations.
0046      * @type int
0047      */
0048     protected $internalPrecision;
0049 
0050     /**
0051      * Whether or not BCMath is available.
0052      * @type bool
0053      */
0054     private $bcmath;
0055 
0056     public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)
0057     {
0058         $this->outputPrecision = $output_precision;
0059         $this->internalPrecision = $internal_precision;
0060         $this->bcmath = !$force_no_bcmath && function_exists('bcmul');
0061     }
0062 
0063     /**
0064      * Converts a length object of one unit into another unit.
0065      * @param HTMLPurifier_Length $length
0066      *      Instance of HTMLPurifier_Length to convert. You must validate()
0067      *      it before passing it here!
0068      * @param string $to_unit
0069      *      Unit to convert to.
0070      * @return HTMLPurifier_Length|bool
0071      * @note
0072      *      About precision: This conversion function pays very special
0073      *      attention to the incoming precision of values and attempts
0074      *      to maintain a number of significant figure. Results are
0075      *      fairly accurate up to nine digits. Some caveats:
0076      *          - If a number is zero-padded as a result of this significant
0077      *            figure tracking, the zeroes will be eliminated.
0078      *          - If a number contains less than four sigfigs ($outputPrecision)
0079      *            and this causes some decimals to be excluded, those
0080      *            decimals will be added on.
0081      */
0082     public function convert($length, $to_unit)
0083     {
0084         if (!$length->isValid()) {
0085             return false;
0086         }
0087 
0088         $n = $length->getN();
0089         $unit = $length->getUnit();
0090 
0091         if ($n === '0' || $unit === false) {
0092             return new HTMLPurifier_Length('0', false);
0093         }
0094 
0095         $state = $dest_state = false;
0096         foreach (self::$units as $k => $x) {
0097             if (isset($x[$unit])) {
0098                 $state = $k;
0099             }
0100             if (isset($x[$to_unit])) {
0101                 $dest_state = $k;
0102             }
0103         }
0104         if (!$state || !$dest_state) {
0105             return false;
0106         }
0107 
0108         // Some calculations about the initial precision of the number;
0109         // this will be useful when we need to do final rounding.
0110         $sigfigs = $this->getSigFigs($n);
0111         if ($sigfigs < $this->outputPrecision) {
0112             $sigfigs = $this->outputPrecision;
0113         }
0114 
0115         // BCMath's internal precision deals only with decimals. Use
0116         // our default if the initial number has no decimals, or increase
0117         // it by how ever many decimals, thus, the number of guard digits
0118         // will always be greater than or equal to internalPrecision.
0119         $log = (int)floor(log(abs($n), 10));
0120         $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
0121 
0122         for ($i = 0; $i < 2; $i++) {
0123 
0124             // Determine what unit IN THIS SYSTEM we need to convert to
0125             if ($dest_state === $state) {
0126                 // Simple conversion
0127                 $dest_unit = $to_unit;
0128             } else {
0129                 // Convert to the smallest unit, pending a system shift
0130                 $dest_unit = self::$units[$state][$dest_state][0];
0131             }
0132 
0133             // Do the conversion if necessary
0134             if ($dest_unit !== $unit) {
0135                 $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
0136                 $n = $this->mul($n, $factor, $cp);
0137                 $unit = $dest_unit;
0138             }
0139 
0140             // Output was zero, so bail out early. Shouldn't ever happen.
0141             if ($n === '') {
0142                 $n = '0';
0143                 $unit = $to_unit;
0144                 break;
0145             }
0146 
0147             // It was a simple conversion, so bail out
0148             if ($dest_state === $state) {
0149                 break;
0150             }
0151 
0152             if ($i !== 0) {
0153                 // Conversion failed! Apparently, the system we forwarded
0154                 // to didn't have this unit. This should never happen!
0155                 return false;
0156             }
0157 
0158             // Pre-condition: $i == 0
0159 
0160             // Perform conversion to next system of units
0161             $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
0162             $unit = self::$units[$state][$dest_state][2];
0163             $state = $dest_state;
0164 
0165             // One more loop around to convert the unit in the new system.
0166 
0167         }
0168 
0169         // Post-condition: $unit == $to_unit
0170         if ($unit !== $to_unit) {
0171             return false;
0172         }
0173 
0174         // Useful for debugging:
0175         //echo "<pre>n";
0176         //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
0177 
0178         $n = $this->round($n, $sigfigs);
0179         if (strpos($n, '.') !== false) {
0180             $n = rtrim($n, '0');
0181         }
0182         $n = rtrim($n, '.');
0183 
0184         return new HTMLPurifier_Length($n, $unit);
0185     }
0186 
0187     /**
0188      * Returns the number of significant figures in a string number.
0189      * @param string $n Decimal number
0190      * @return int number of sigfigs
0191      */
0192     public function getSigFigs($n)
0193     {
0194         $n = ltrim($n, '0+-');
0195         $dp = strpos($n, '.'); // decimal position
0196         if ($dp === false) {
0197             $sigfigs = strlen(rtrim($n, '0'));
0198         } else {
0199             $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character
0200             if ($dp !== 0) {
0201                 $sigfigs--;
0202             }
0203         }
0204         return $sigfigs;
0205     }
0206 
0207     /**
0208      * Adds two numbers, using arbitrary precision when available.
0209      * @param string $s1
0210      * @param string $s2
0211      * @param int $scale
0212      * @return string
0213      */
0214     private function add($s1, $s2, $scale)
0215     {
0216         if ($this->bcmath) {
0217             return bcadd($s1, $s2, $scale);
0218         } else {
0219             return $this->scale((float)$s1 + (float)$s2, $scale);
0220         }
0221     }
0222 
0223     /**
0224      * Multiples two numbers, using arbitrary precision when available.
0225      * @param string $s1
0226      * @param string $s2
0227      * @param int $scale
0228      * @return string
0229      */
0230     private function mul($s1, $s2, $scale)
0231     {
0232         if ($this->bcmath) {
0233             return bcmul($s1, $s2, $scale);
0234         } else {
0235             return $this->scale((float)$s1 * (float)$s2, $scale);
0236         }
0237     }
0238 
0239     /**
0240      * Divides two numbers, using arbitrary precision when available.
0241      * @param string $s1
0242      * @param string $s2
0243      * @param int $scale
0244      * @return string
0245      */
0246     private function div($s1, $s2, $scale)
0247     {
0248         if ($this->bcmath) {
0249             return bcdiv($s1, $s2, $scale);
0250         } else {
0251             return $this->scale((float)$s1 / (float)$s2, $scale);
0252         }
0253     }
0254 
0255     /**
0256      * Rounds a number according to the number of sigfigs it should have,
0257      * using arbitrary precision when available.
0258      * @param float $n
0259      * @param int $sigfigs
0260      * @return string
0261      */
0262     private function round($n, $sigfigs)
0263     {
0264         $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1
0265         $rp = $sigfigs - $new_log - 1; // Number of decimal places needed
0266         $neg = $n < 0 ? '-' : ''; // Negative sign
0267         if ($this->bcmath) {
0268             if ($rp >= 0) {
0269                 $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);
0270                 $n = bcdiv($n, '1', $rp);
0271             } else {
0272                 // This algorithm partially depends on the standardized
0273                 // form of numbers that comes out of bcmath.
0274                 $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);
0275                 $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);
0276             }
0277             return $n;
0278         } else {
0279             return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
0280         }
0281     }
0282 
0283     /**
0284      * Scales a float to $scale digits right of decimal point, like BCMath.
0285      * @param float $r
0286      * @param int $scale
0287      * @return string
0288      */
0289     private function scale($r, $scale)
0290     {
0291         if ($scale < 0) {
0292             // The f sprintf type doesn't support negative numbers, so we
0293             // need to cludge things manually. First get the string.
0294             $r = sprintf('%.0f', (float)$r);
0295             // Due to floating point precision loss, $r will more than likely
0296             // look something like 4652999999999.9234. We grab one more digit
0297             // than we need to precise from $r and then use that to round
0298             // appropriately.
0299             $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1);
0300             // Now we return it, truncating the zero that was rounded off.
0301             return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
0302         }
0303         return sprintf('%.' . $scale . 'f', (float)$r);
0304     }
0305 }
0306 
0307 // vim: et sw=4 sts=4