Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

308 linhas
9.9KB

  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. * @type int
  37. */
  38. protected $outputPrecision;
  39. /**
  40. * Bcmath precision for internal calculations.
  41. * @type int
  42. */
  43. protected $internalPrecision;
  44. /**
  45. * Whether or not BCMath is available.
  46. * @type bool
  47. */
  48. private $bcmath;
  49. public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)
  50. {
  51. $this->outputPrecision = $output_precision;
  52. $this->internalPrecision = $internal_precision;
  53. $this->bcmath = !$force_no_bcmath && function_exists('bcmul');
  54. }
  55. /**
  56. * Converts a length object of one unit into another unit.
  57. * @param HTMLPurifier_Length $length
  58. * Instance of HTMLPurifier_Length to convert. You must validate()
  59. * it before passing it here!
  60. * @param string $to_unit
  61. * Unit to convert to.
  62. * @return HTMLPurifier_Length|bool
  63. * @note
  64. * About precision: This conversion function pays very special
  65. * attention to the incoming precision of values and attempts
  66. * to maintain a number of significant figure. Results are
  67. * fairly accurate up to nine digits. Some caveats:
  68. * - If a number is zero-padded as a result of this significant
  69. * figure tracking, the zeroes will be eliminated.
  70. * - If a number contains less than four sigfigs ($outputPrecision)
  71. * and this causes some decimals to be excluded, those
  72. * decimals will be added on.
  73. */
  74. public function convert($length, $to_unit)
  75. {
  76. if (!$length->isValid()) {
  77. return false;
  78. }
  79. $n = $length->getN();
  80. $unit = $length->getUnit();
  81. if ($n === '0' || $unit === false) {
  82. return new HTMLPurifier_Length('0', false);
  83. }
  84. $state = $dest_state = false;
  85. foreach (self::$units as $k => $x) {
  86. if (isset($x[$unit])) {
  87. $state = $k;
  88. }
  89. if (isset($x[$to_unit])) {
  90. $dest_state = $k;
  91. }
  92. }
  93. if (!$state || !$dest_state) {
  94. return false;
  95. }
  96. // Some calculations about the initial precision of the number;
  97. // this will be useful when we need to do final rounding.
  98. $sigfigs = $this->getSigFigs($n);
  99. if ($sigfigs < $this->outputPrecision) {
  100. $sigfigs = $this->outputPrecision;
  101. }
  102. // BCMath's internal precision deals only with decimals. Use
  103. // our default if the initial number has no decimals, or increase
  104. // it by how ever many decimals, thus, the number of guard digits
  105. // will always be greater than or equal to internalPrecision.
  106. $log = (int)floor(log(abs($n), 10));
  107. $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
  108. for ($i = 0; $i < 2; $i++) {
  109. // Determine what unit IN THIS SYSTEM we need to convert to
  110. if ($dest_state === $state) {
  111. // Simple conversion
  112. $dest_unit = $to_unit;
  113. } else {
  114. // Convert to the smallest unit, pending a system shift
  115. $dest_unit = self::$units[$state][$dest_state][0];
  116. }
  117. // Do the conversion if necessary
  118. if ($dest_unit !== $unit) {
  119. $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
  120. $n = $this->mul($n, $factor, $cp);
  121. $unit = $dest_unit;
  122. }
  123. // Output was zero, so bail out early. Shouldn't ever happen.
  124. if ($n === '') {
  125. $n = '0';
  126. $unit = $to_unit;
  127. break;
  128. }
  129. // It was a simple conversion, so bail out
  130. if ($dest_state === $state) {
  131. break;
  132. }
  133. if ($i !== 0) {
  134. // Conversion failed! Apparently, the system we forwarded
  135. // to didn't have this unit. This should never happen!
  136. return false;
  137. }
  138. // Pre-condition: $i == 0
  139. // Perform conversion to next system of units
  140. $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
  141. $unit = self::$units[$state][$dest_state][2];
  142. $state = $dest_state;
  143. // One more loop around to convert the unit in the new system.
  144. }
  145. // Post-condition: $unit == $to_unit
  146. if ($unit !== $to_unit) {
  147. return false;
  148. }
  149. // Useful for debugging:
  150. //echo "<pre>n";
  151. //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
  152. $n = $this->round($n, $sigfigs);
  153. if (strpos($n, '.') !== false) {
  154. $n = rtrim($n, '0');
  155. }
  156. $n = rtrim($n, '.');
  157. return new HTMLPurifier_Length($n, $unit);
  158. }
  159. /**
  160. * Returns the number of significant figures in a string number.
  161. * @param string $n Decimal number
  162. * @return int number of sigfigs
  163. */
  164. public function getSigFigs($n)
  165. {
  166. $n = ltrim($n, '0+-');
  167. $dp = strpos($n, '.'); // decimal position
  168. if ($dp === false) {
  169. $sigfigs = strlen(rtrim($n, '0'));
  170. } else {
  171. $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character
  172. if ($dp !== 0) {
  173. $sigfigs--;
  174. }
  175. }
  176. return $sigfigs;
  177. }
  178. /**
  179. * Adds two numbers, using arbitrary precision when available.
  180. * @param string $s1
  181. * @param string $s2
  182. * @param int $scale
  183. * @return string
  184. */
  185. private function add($s1, $s2, $scale)
  186. {
  187. if ($this->bcmath) {
  188. return bcadd($s1, $s2, $scale);
  189. } else {
  190. return $this->scale((float)$s1 + (float)$s2, $scale);
  191. }
  192. }
  193. /**
  194. * Multiples two numbers, using arbitrary precision when available.
  195. * @param string $s1
  196. * @param string $s2
  197. * @param int $scale
  198. * @return string
  199. */
  200. private function mul($s1, $s2, $scale)
  201. {
  202. if ($this->bcmath) {
  203. return bcmul($s1, $s2, $scale);
  204. } else {
  205. return $this->scale((float)$s1 * (float)$s2, $scale);
  206. }
  207. }
  208. /**
  209. * Divides two numbers, using arbitrary precision when available.
  210. * @param string $s1
  211. * @param string $s2
  212. * @param int $scale
  213. * @return string
  214. */
  215. private function div($s1, $s2, $scale)
  216. {
  217. if ($this->bcmath) {
  218. return bcdiv($s1, $s2, $scale);
  219. } else {
  220. return $this->scale((float)$s1 / (float)$s2, $scale);
  221. }
  222. }
  223. /**
  224. * Rounds a number according to the number of sigfigs it should have,
  225. * using arbitrary precision when available.
  226. * @param float $n
  227. * @param int $sigfigs
  228. * @return string
  229. */
  230. private function round($n, $sigfigs)
  231. {
  232. $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1
  233. $rp = $sigfigs - $new_log - 1; // Number of decimal places needed
  234. $neg = $n < 0 ? '-' : ''; // Negative sign
  235. if ($this->bcmath) {
  236. if ($rp >= 0) {
  237. $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);
  238. $n = bcdiv($n, '1', $rp);
  239. } else {
  240. // This algorithm partially depends on the standardized
  241. // form of numbers that comes out of bcmath.
  242. $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);
  243. $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);
  244. }
  245. return $n;
  246. } else {
  247. return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
  248. }
  249. }
  250. /**
  251. * Scales a float to $scale digits right of decimal point, like BCMath.
  252. * @param float $r
  253. * @param int $scale
  254. * @return string
  255. */
  256. private function scale($r, $scale)
  257. {
  258. if ($scale < 0) {
  259. // The f sprintf type doesn't support negative numbers, so we
  260. // need to cludge things manually. First get the string.
  261. $r = sprintf('%.0f', (float)$r);
  262. // Due to floating point precision loss, $r will more than likely
  263. // look something like 4652999999999.9234. We grab one more digit
  264. // than we need to precise from $r and then use that to round
  265. // appropriately.
  266. $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1);
  267. // Now we return it, truncating the zero that was rounded off.
  268. return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
  269. }
  270. return sprintf('%.' . $scale . 'f', (float)$r);
  271. }
  272. }
  273. // vim: et sw=4 sts=4