--- /dev/null
+<?php\r
+\r
+/**\r
+ * Class for converting between different unit-lengths as specified by\r
+ * CSS.\r
+ */\r
+class HTMLPurifier_UnitConverter\r
+{\r
+\r
+ const ENGLISH = 1;\r
+ const METRIC = 2;\r
+ const DIGITAL = 3;\r
+\r
+ /**\r
+ * Units information array. Units are grouped into measuring systems\r
+ * (English, Metric), and are assigned an integer representing\r
+ * the conversion factor between that unit and the smallest unit in\r
+ * the system. Numeric indexes are actually magical constants that\r
+ * encode conversion data from one system to the next, with a O(n^2)\r
+ * constraint on memory (this is generally not a problem, since\r
+ * the number of measuring systems is small.)\r
+ */\r
+ protected static $units = array(\r
+ self::ENGLISH => array(\r
+ 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary\r
+ 'pt' => 4,\r
+ 'pc' => 48,\r
+ 'in' => 288,\r
+ self::METRIC => array('pt', '0.352777778', 'mm'),\r
+ ),\r
+ self::METRIC => array(\r
+ 'mm' => 1,\r
+ 'cm' => 10,\r
+ self::ENGLISH => array('mm', '2.83464567', 'pt'),\r
+ ),\r
+ );\r
+\r
+ /**\r
+ * Minimum bcmath precision for output.\r
+ * @type int\r
+ */\r
+ protected $outputPrecision;\r
+\r
+ /**\r
+ * Bcmath precision for internal calculations.\r
+ * @type int\r
+ */\r
+ protected $internalPrecision;\r
+\r
+ /**\r
+ * Whether or not BCMath is available.\r
+ * @type bool\r
+ */\r
+ private $bcmath;\r
+\r
+ public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)\r
+ {\r
+ $this->outputPrecision = $output_precision;\r
+ $this->internalPrecision = $internal_precision;\r
+ $this->bcmath = !$force_no_bcmath && function_exists('bcmul');\r
+ }\r
+\r
+ /**\r
+ * Converts a length object of one unit into another unit.\r
+ * @param HTMLPurifier_Length $length\r
+ * Instance of HTMLPurifier_Length to convert. You must validate()\r
+ * it before passing it here!\r
+ * @param string $to_unit\r
+ * Unit to convert to.\r
+ * @return HTMLPurifier_Length|bool\r
+ * @note\r
+ * About precision: This conversion function pays very special\r
+ * attention to the incoming precision of values and attempts\r
+ * to maintain a number of significant figure. Results are\r
+ * fairly accurate up to nine digits. Some caveats:\r
+ * - If a number is zero-padded as a result of this significant\r
+ * figure tracking, the zeroes will be eliminated.\r
+ * - If a number contains less than four sigfigs ($outputPrecision)\r
+ * and this causes some decimals to be excluded, those\r
+ * decimals will be added on.\r
+ */\r
+ public function convert($length, $to_unit)\r
+ {\r
+ if (!$length->isValid()) {\r
+ return false;\r
+ }\r
+\r
+ $n = $length->getN();\r
+ $unit = $length->getUnit();\r
+\r
+ if ($n === '0' || $unit === false) {\r
+ return new HTMLPurifier_Length('0', false);\r
+ }\r
+\r
+ $state = $dest_state = false;\r
+ foreach (self::$units as $k => $x) {\r
+ if (isset($x[$unit])) {\r
+ $state = $k;\r
+ }\r
+ if (isset($x[$to_unit])) {\r
+ $dest_state = $k;\r
+ }\r
+ }\r
+ if (!$state || !$dest_state) {\r
+ return false;\r
+ }\r
+\r
+ // Some calculations about the initial precision of the number;\r
+ // this will be useful when we need to do final rounding.\r
+ $sigfigs = $this->getSigFigs($n);\r
+ if ($sigfigs < $this->outputPrecision) {\r
+ $sigfigs = $this->outputPrecision;\r
+ }\r
+\r
+ // BCMath's internal precision deals only with decimals. Use\r
+ // our default if the initial number has no decimals, or increase\r
+ // it by how ever many decimals, thus, the number of guard digits\r
+ // will always be greater than or equal to internalPrecision.\r
+ $log = (int)floor(log(abs($n), 10));\r
+ $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision\r
+\r
+ for ($i = 0; $i < 2; $i++) {\r
+\r
+ // Determine what unit IN THIS SYSTEM we need to convert to\r
+ if ($dest_state === $state) {\r
+ // Simple conversion\r
+ $dest_unit = $to_unit;\r
+ } else {\r
+ // Convert to the smallest unit, pending a system shift\r
+ $dest_unit = self::$units[$state][$dest_state][0];\r
+ }\r
+\r
+ // Do the conversion if necessary\r
+ if ($dest_unit !== $unit) {\r
+ $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);\r
+ $n = $this->mul($n, $factor, $cp);\r
+ $unit = $dest_unit;\r
+ }\r
+\r
+ // Output was zero, so bail out early. Shouldn't ever happen.\r
+ if ($n === '') {\r
+ $n = '0';\r
+ $unit = $to_unit;\r
+ break;\r
+ }\r
+\r
+ // It was a simple conversion, so bail out\r
+ if ($dest_state === $state) {\r
+ break;\r
+ }\r
+\r
+ if ($i !== 0) {\r
+ // Conversion failed! Apparently, the system we forwarded\r
+ // to didn't have this unit. This should never happen!\r
+ return false;\r
+ }\r
+\r
+ // Pre-condition: $i == 0\r
+\r
+ // Perform conversion to next system of units\r
+ $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);\r
+ $unit = self::$units[$state][$dest_state][2];\r
+ $state = $dest_state;\r
+\r
+ // One more loop around to convert the unit in the new system.\r
+\r
+ }\r
+\r
+ // Post-condition: $unit == $to_unit\r
+ if ($unit !== $to_unit) {\r
+ return false;\r
+ }\r
+\r
+ // Useful for debugging:\r
+ //echo "<pre>n";\r
+ //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";\r
+\r
+ $n = $this->round($n, $sigfigs);\r
+ if (strpos($n, '.') !== false) {\r
+ $n = rtrim($n, '0');\r
+ }\r
+ $n = rtrim($n, '.');\r
+\r
+ return new HTMLPurifier_Length($n, $unit);\r
+ }\r
+\r
+ /**\r
+ * Returns the number of significant figures in a string number.\r
+ * @param string $n Decimal number\r
+ * @return int number of sigfigs\r
+ */\r
+ public function getSigFigs($n)\r
+ {\r
+ $n = ltrim($n, '0+-');\r
+ $dp = strpos($n, '.'); // decimal position\r
+ if ($dp === false) {\r
+ $sigfigs = strlen(rtrim($n, '0'));\r
+ } else {\r
+ $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character\r
+ if ($dp !== 0) {\r
+ $sigfigs--;\r
+ }\r
+ }\r
+ return $sigfigs;\r
+ }\r
+\r
+ /**\r
+ * Adds two numbers, using arbitrary precision when available.\r
+ * @param string $s1\r
+ * @param string $s2\r
+ * @param int $scale\r
+ * @return string\r
+ */\r
+ private function add($s1, $s2, $scale)\r
+ {\r
+ if ($this->bcmath) {\r
+ return bcadd($s1, $s2, $scale);\r
+ } else {\r
+ return $this->scale((float)$s1 + (float)$s2, $scale);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Multiples two numbers, using arbitrary precision when available.\r
+ * @param string $s1\r
+ * @param string $s2\r
+ * @param int $scale\r
+ * @return string\r
+ */\r
+ private function mul($s1, $s2, $scale)\r
+ {\r
+ if ($this->bcmath) {\r
+ return bcmul($s1, $s2, $scale);\r
+ } else {\r
+ return $this->scale((float)$s1 * (float)$s2, $scale);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Divides two numbers, using arbitrary precision when available.\r
+ * @param string $s1\r
+ * @param string $s2\r
+ * @param int $scale\r
+ * @return string\r
+ */\r
+ private function div($s1, $s2, $scale)\r
+ {\r
+ if ($this->bcmath) {\r
+ return bcdiv($s1, $s2, $scale);\r
+ } else {\r
+ return $this->scale((float)$s1 / (float)$s2, $scale);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Rounds a number according to the number of sigfigs it should have,\r
+ * using arbitrary precision when available.\r
+ * @param float $n\r
+ * @param int $sigfigs\r
+ * @return string\r
+ */\r
+ private function round($n, $sigfigs)\r
+ {\r
+ $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1\r
+ $rp = $sigfigs - $new_log - 1; // Number of decimal places needed\r
+ $neg = $n < 0 ? '-' : ''; // Negative sign\r
+ if ($this->bcmath) {\r
+ if ($rp >= 0) {\r
+ $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);\r
+ $n = bcdiv($n, '1', $rp);\r
+ } else {\r
+ // This algorithm partially depends on the standardized\r
+ // form of numbers that comes out of bcmath.\r
+ $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);\r
+ $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);\r
+ }\r
+ return $n;\r
+ } else {\r
+ return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Scales a float to $scale digits right of decimal point, like BCMath.\r
+ * @param float $r\r
+ * @param int $scale\r
+ * @return string\r
+ */\r
+ private function scale($r, $scale)\r
+ {\r
+ if ($scale < 0) {\r
+ // The f sprintf type doesn't support negative numbers, so we\r
+ // need to cludge things manually. First get the string.\r
+ $r = sprintf('%.0f', (float)$r);\r
+ // Due to floating point precision loss, $r will more than likely\r
+ // look something like 4652999999999.9234. We grab one more digit\r
+ // than we need to precise from $r and then use that to round\r
+ // appropriately.\r
+ $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1);\r
+ // Now we return it, truncating the zero that was rounded off.\r
+ return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);\r
+ }\r
+ return sprintf('%.' . $scale . 'f', (float)$r);\r
+ }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r