Drupal investigation

random_int.php 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php
  2. if (!is_callable('random_int')) {
  3. /**
  4. * Random_* Compatibility Library
  5. * for using the new PHP 7 random_* API in PHP 5 projects
  6. *
  7. * The MIT License (MIT)
  8. *
  9. * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27. * SOFTWARE.
  28. */
  29. /**
  30. * Fetch a random integer between $min and $max inclusive
  31. *
  32. * @param int $min
  33. * @param int $max
  34. *
  35. * @throws Exception
  36. *
  37. * @return int
  38. */
  39. function random_int($min, $max)
  40. {
  41. /**
  42. * Type and input logic checks
  43. *
  44. * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
  45. * (non-inclusive), it will sanely cast it to an int. If you it's equal to
  46. * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats
  47. * lose precision, so the <= and => operators might accidentally let a float
  48. * through.
  49. */
  50. try {
  51. $min = RandomCompat_intval($min);
  52. } catch (TypeError $ex) {
  53. throw new TypeError(
  54. 'random_int(): $min must be an integer'
  55. );
  56. }
  57. try {
  58. $max = RandomCompat_intval($max);
  59. } catch (TypeError $ex) {
  60. throw new TypeError(
  61. 'random_int(): $max must be an integer'
  62. );
  63. }
  64. /**
  65. * Now that we've verified our weak typing system has given us an integer,
  66. * let's validate the logic then we can move forward with generating random
  67. * integers along a given range.
  68. */
  69. if ($min > $max) {
  70. throw new Error(
  71. 'Minimum value must be less than or equal to the maximum value'
  72. );
  73. }
  74. if ($max === $min) {
  75. return $min;
  76. }
  77. /**
  78. * Initialize variables to 0
  79. *
  80. * We want to store:
  81. * $bytes => the number of random bytes we need
  82. * $mask => an integer bitmask (for use with the &) operator
  83. * so we can minimize the number of discards
  84. */
  85. $attempts = $bits = $bytes = $mask = $valueShift = 0;
  86. /**
  87. * At this point, $range is a positive number greater than 0. It might
  88. * overflow, however, if $max - $min > PHP_INT_MAX. PHP will cast it to
  89. * a float and we will lose some precision.
  90. */
  91. $range = $max - $min;
  92. /**
  93. * Test for integer overflow:
  94. */
  95. if (!is_int($range)) {
  96. /**
  97. * Still safely calculate wider ranges.
  98. * Provided by @CodesInChaos, @oittaa
  99. *
  100. * @ref https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
  101. *
  102. * We use ~0 as a mask in this case because it generates all 1s
  103. *
  104. * @ref https://eval.in/400356 (32-bit)
  105. * @ref http://3v4l.org/XX9r5 (64-bit)
  106. */
  107. $bytes = PHP_INT_SIZE;
  108. $mask = ~0;
  109. } else {
  110. /**
  111. * $bits is effectively ceil(log($range, 2)) without dealing with
  112. * type juggling
  113. */
  114. while ($range > 0) {
  115. if ($bits % 8 === 0) {
  116. ++$bytes;
  117. }
  118. ++$bits;
  119. $range >>= 1;
  120. $mask = $mask << 1 | 1;
  121. }
  122. $valueShift = $min;
  123. }
  124. $val = 0;
  125. /**
  126. * Now that we have our parameters set up, let's begin generating
  127. * random integers until one falls between $min and $max
  128. */
  129. do {
  130. /**
  131. * The rejection probability is at most 0.5, so this corresponds
  132. * to a failure probability of 2^-128 for a working RNG
  133. */
  134. if ($attempts > 128) {
  135. throw new Exception(
  136. 'random_int: RNG is broken - too many rejections'
  137. );
  138. }
  139. /**
  140. * Let's grab the necessary number of random bytes
  141. */
  142. $randomByteString = random_bytes($bytes);
  143. /**
  144. * Let's turn $randomByteString into an integer
  145. *
  146. * This uses bitwise operators (<< and |) to build an integer
  147. * out of the values extracted from ord()
  148. *
  149. * Example: [9F] | [6D] | [32] | [0C] =>
  150. * 159 + 27904 + 3276800 + 201326592 =>
  151. * 204631455
  152. */
  153. $val &= 0;
  154. for ($i = 0; $i < $bytes; ++$i) {
  155. $val |= ord($randomByteString[$i]) << ($i * 8);
  156. }
  157. /**
  158. * Apply mask
  159. */
  160. $val &= $mask;
  161. $val += $valueShift;
  162. ++$attempts;
  163. /**
  164. * If $val overflows to a floating point number,
  165. * ... or is larger than $max,
  166. * ... or smaller than $min,
  167. * then try again.
  168. */
  169. } while (!is_int($val) || $val > $max || $val < $min);
  170. return (int)$val;
  171. }
  172. }