diff options
Diffstat (limited to 'core/Common.php')
-rw-r--r-- | core/Common.php | 49 |
1 files changed, 43 insertions, 6 deletions
diff --git a/core/Common.php b/core/Common.php index c332e682f2..1616e56505 100644 --- a/core/Common.php +++ b/core/Common.php @@ -504,17 +504,54 @@ class Common */ /** + * Generates a random integer + * + * @param int $min + * @param null|int $max Defaults to max int value + * @return int|null + */ + public static function getRandomInt($min = 0, $max = null) + { + $rand = null; + + if (function_exists('random_int')) { + try { + if (!isset($max)) { + $max = PHP_INT_MAX; + } + $rand = random_int($min, $max); + } catch (Exception $e) { + // If none of the crypto sources are available, an Exception will be thrown. + $rand = null; + } + } + + if (!isset($rand)) { + if (function_exists('mt_rand')) { + if (!isset($max)) { + $max = mt_getrandmax(); + } + $rand = mt_rand($min, $max); + } else { + if (!isset($max)) { + $max = getrandmax(); + } + + $rand = rand($min, $max); + } + } + + return $rand; + } + + /** * Returns a 32 characters long uniq ID * * @return string 32 chars */ public static function generateUniqId() { - if (function_exists('mt_rand')) { - $rand = mt_rand(); - } else { - $rand = rand(); - } + $rand = self::getRandomInt(); return md5(uniqid($rand, true)); } @@ -558,7 +595,7 @@ class Common $str = ''; for ($i = 0; $i < $length; $i++) { - $rand_key = mt_rand(0, strlen($chars) - 1); + $rand_key = self::getRandomInt(0, strlen($chars) - 1); $str .= substr($chars, $rand_key, 1); } |