UnitConverter.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. /**
  3. * Class for converting between different unit-lengths as specified by
  4. * CSS.
  5. */
  6. class HTMLPurifier_UnitConverter
  7. {
  8. const ENGLISH = 1;
  9. const METRIC = 2;
  10. const DIGITAL = 3;
  11. /**
  12. * Units information array. Units are grouped into measuring systems
  13. * (English, Metric), and are assigned an integer representing
  14. * the conversion factor between that unit and the smallest unit in
  15. * the system. Numeric indexes are actually magical constants that
  16. * encode conversion data from one system to the next, with a O(n^2)
  17. * constraint on memory (this is generally not a problem, since
  18. * the number of measuring systems is small.)
  19. */
  20. protected static $units = array(
  21. self::ENGLISH => array(
  22. 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary
  23. 'pt' => 4,
  24. 'pc' => 48,
  25. 'in' => 288,
  26. self::METRIC => array('pt', '0.352777778', 'mm'),
  27. ),
  28. self::METRIC => array(
  29. 'mm' => 1,
  30. 'cm' => 10,
  31. self::ENGLISH => array('mm', '2.83464567', 'pt'),
  32. ),
  33. );
  34. /**
  35. * Minimum bcmath precision for output.
  36. */
  37. protected $outputPrecision;
  38. /**
  39. * Bcmath precision for internal calculations.
  40. */
  41. protected $internalPrecision;
  42. /**
  43. * Whether or not BCMath is available
  44. */
  45. private $bcmath;
  46. public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) {
  47. $this->outputPrecision = $output_precision;
  48. $this->internalPrecision = $internal_precision;
  49. $this->bcmath = !$force_no_bcmath && function_exists('bcmul');
  50. }
  51. /**
  52. * Converts a length object of one unit into another unit.
  53. * @param HTMLPurifier_Length $length
  54. * Instance of HTMLPurifier_Length to convert. You must validate()
  55. * it before passing it here!
  56. * @param string $to_unit
  57. * Unit to convert to.
  58. * @note
  59. * About precision: This conversion function pays very special
  60. * attention to the incoming precision of values and attempts
  61. * to maintain a number of significant figure. Results are
  62. * fairly accurate up to nine digits. Some caveats:
  63. * - If a number is zero-padded as a result of this significant
  64. * figure tracking, the zeroes will be eliminated.
  65. * - If a number contains less than four sigfigs ($outputPrecision)
  66. * and this causes some decimals to be excluded, those
  67. * decimals will be added on.
  68. */
  69. public function convert($length, $to_unit) {
  70. if (!$length->isValid()) return false;
  71. $n = $length->getN();
  72. $unit = $length->getUnit();
  73. if ($n === '0' || $unit === false) {
  74. return new HTMLPurifier_Length('0', false);
  75. }
  76. $state = $dest_state = false;
  77. foreach (self::$units as $k => $x) {
  78. if (isset($x[$unit])) $state = $k;
  79. if (isset($x[$to_unit])) $dest_state = $k;
  80. }
  81. if (!$state || !$dest_state) return false;
  82. // Some calculations about the initial precision of the number;
  83. // this will be useful when we need to do final rounding.
  84. $sigfigs = $this->getSigFigs($n);
  85. if ($sigfigs < $this->outputPrecision) $sigfigs = $this->outputPrecision;
  86. // BCMath's internal precision deals only with decimals. Use
  87. // our default if the initial number has no decimals, or increase
  88. // it by how ever many decimals, thus, the number of guard digits
  89. // will always be greater than or equal to internalPrecision.
  90. $log = (int) floor(log(abs($n), 10));
  91. $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
  92. for ($i = 0; $i < 2; $i++) {
  93. // Determine what unit IN THIS SYSTEM we need to convert to
  94. if ($dest_state === $state) {
  95. // Simple conversion
  96. $dest_unit = $to_unit;
  97. } else {
  98. // Convert to the smallest unit, pending a system shift
  99. $dest_unit = self::$units[$state][$dest_state][0];
  100. }
  101. // Do the conversion if necessary
  102. if ($dest_unit !== $unit) {
  103. $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
  104. $n = $this->mul($n, $factor, $cp);
  105. $unit = $dest_unit;
  106. }
  107. // Output was zero, so bail out early. Shouldn't ever happen.
  108. if ($n === '') {
  109. $n = '0';
  110. $unit = $to_unit;
  111. break;
  112. }
  113. // It was a simple conversion, so bail out
  114. if ($dest_state === $state) {
  115. break;
  116. }
  117. if ($i !== 0) {
  118. // Conversion failed! Apparently, the system we forwarded
  119. // to didn't have this unit. This should never happen!
  120. return false;
  121. }
  122. // Pre-condition: $i == 0
  123. // Perform conversion to next system of units
  124. $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
  125. $unit = self::$units[$state][$dest_state][2];
  126. $state = $dest_state;
  127. // One more loop around to convert the unit in the new system.
  128. }
  129. // Post-condition: $unit == $to_unit
  130. if ($unit !== $to_unit) return false;
  131. // Useful for debugging:
  132. //echo "<pre>n";
  133. //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
  134. $n = $this->round($n, $sigfigs);
  135. if (strpos($n, '.') !== false) $n = rtrim($n, '0');
  136. $n = rtrim($n, '.');
  137. return new HTMLPurifier_Length($n, $unit);
  138. }
  139. /**
  140. * Returns the number of significant figures in a string number.
  141. * @param string $n Decimal number
  142. * @return int number of sigfigs
  143. */
  144. public function getSigFigs($n) {
  145. $n = ltrim($n, '0+-');
  146. $dp = strpos($n, '.'); // decimal position
  147. if ($dp === false) {
  148. $sigfigs = strlen(rtrim($n, '0'));
  149. } else {
  150. $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character
  151. if ($dp !== 0) $sigfigs--;
  152. }
  153. return $sigfigs;
  154. }
  155. /**
  156. * Adds two numbers, using arbitrary precision when available.
  157. */
  158. private function add($s1, $s2, $scale) {
  159. if ($this->bcmath) return bcadd($s1, $s2, $scale);
  160. else return $this->scale($s1 + $s2, $scale);
  161. }
  162. /**
  163. * Multiples two numbers, using arbitrary precision when available.
  164. */
  165. private function mul($s1, $s2, $scale) {
  166. if ($this->bcmath) return bcmul($s1, $s2, $scale);
  167. else return $this->scale($s1 * $s2, $scale);
  168. }
  169. /**
  170. * Divides two numbers, using arbitrary precision when available.
  171. */
  172. private function div($s1, $s2, $scale) {
  173. if ($this->bcmath) return bcdiv($s1, $s2, $scale);
  174. else return $this->scale($s1 / $s2, $scale);
  175. }
  176. /**
  177. * Rounds a number according to the number of sigfigs it should have,
  178. * using arbitrary precision when available.
  179. */
  180. private function round($n, $sigfigs) {
  181. $new_log = (int) floor(log(abs($n), 10)); // Number of digits left of decimal - 1
  182. $rp = $sigfigs - $new_log - 1; // Number of decimal places needed
  183. $neg = $n < 0 ? '-' : ''; // Negative sign
  184. if ($this->bcmath) {
  185. if ($rp >= 0) {
  186. $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);
  187. $n = bcdiv($n, '1', $rp);
  188. } else {
  189. // This algorithm partially depends on the standardized
  190. // form of numbers that comes out of bcmath.
  191. $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);
  192. $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);
  193. }
  194. return $n;
  195. } else {
  196. return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
  197. }
  198. }
  199. /**
  200. * Scales a float to $scale digits right of decimal point, like BCMath.
  201. */
  202. private function scale($r, $scale) {
  203. if ($scale < 0) {
  204. // The f sprintf type doesn't support negative numbers, so we
  205. // need to cludge things manually. First get the string.
  206. $r = sprintf('%.0f', (float) $r);
  207. // Due to floating point precision loss, $r will more than likely
  208. // look something like 4652999999999.9234. We grab one more digit
  209. // than we need to precise from $r and then use that to round
  210. // appropriately.
  211. $precise = (string) round(substr($r, 0, strlen($r) + $scale), -1);
  212. // Now we return it, truncating the zero that was rounded off.
  213. return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
  214. }
  215. return sprintf('%.' . $scale . 'f', (float) $r);
  216. }
  217. }
  218. // vim: et sw=4 sts=4