1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Utils;
9:
10:
11: 12: 13:
14: class Random
15: {
16:
17: 18: 19: 20: 21: 22:
23: public static function generate($length = 10, $charlist = '0-9a-z')
24: {
25: $charlist = count_chars(preg_replace_callback('#.-.#', function ($m) {
26: return implode('', range($m[0][0], $m[0][2]));
27: }, $charlist), 3);
28: $chLen = strlen($charlist);
29:
30: if ($length < 1) {
31: return '';
32: } elseif ($chLen < 2) {
33: return str_repeat($charlist, $length);
34: }
35:
36: $res = '';
37: if (PHP_VERSION_ID >= 70000) {
38: for ($i = 0; $i < $length; $i++) {
39: $res .= $charlist[random_int(0, $chLen - 1)];
40: }
41: return $res;
42: }
43:
44: $windows = defined('PHP_WINDOWS_VERSION_BUILD');
45: $bytes = '';
46: if (function_exists('openssl_random_pseudo_bytes')
47: && (PHP_VERSION_ID >= 50400 || !defined('PHP_WINDOWS_VERSION_BUILD'))
48: ) {
49: $bytes = openssl_random_pseudo_bytes($length, $secure);
50: if (!$secure) {
51: $bytes = '';
52: }
53: }
54: if (strlen($bytes) < $length && function_exists('mcrypt_create_iv') && (PHP_VERSION_ID >= 50307 || !$windows)) {
55: $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
56: }
57: if (strlen($bytes) < $length && !$windows && @is_readable('/dev/urandom')) {
58: $bytes = file_get_contents('/dev/urandom', FALSE, NULL, -1, $length);
59: }
60: if (strlen($bytes) < $length) {
61: $rand3 = md5(serialize($_SERVER), TRUE);
62: $charlist = str_shuffle($charlist);
63: for ($i = 0; $i < $length; $i++) {
64: if ($i % 5 === 0) {
65: list($rand1, $rand2) = explode(' ', microtime());
66: $rand1 += lcg_value();
67: }
68: $rand1 *= $chLen;
69: $res .= $charlist[($rand1 + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
70: $rand1 -= (int) $rand1;
71: }
72: return $res;
73: }
74:
75: for ($i = 0; $i < $length; $i++) {
76: $res .= $charlist[($i + ord($bytes[$i])) % $chLen];
77: }
78: return $res;
79: }
80:
81: }
82: