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: if ($length === 0) {
26: return '';
27: }
28:
29: $charlist = str_shuffle(preg_replace_callback('#.-.#', function ($m) {
30: return implode('', range($m[0][0], $m[0][2]));
31: }, $charlist));
32: $chLen = strlen($charlist);
33:
34: $windows = defined('PHP_WINDOWS_VERSION_BUILD');
35: if (function_exists('openssl_random_pseudo_bytes')
36: && (PHP_VERSION_ID >= 50400 || !defined('PHP_WINDOWS_VERSION_BUILD'))
37: ) {
38: $rand3 = openssl_random_pseudo_bytes($length);
39: }
40: if (empty($rand3) && function_exists('mcrypt_create_iv') && (PHP_VERSION_ID >= 50307 || !$windows)) {
41: $rand3 = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
42: }
43: if (empty($rand3) && !$windows && @is_readable('/dev/urandom')) {
44: $rand3 = file_get_contents('/dev/urandom', FALSE, NULL, -1, $length);
45: }
46: if (empty($rand3)) {
47: static $cache;
48: $rand3 = $cache ?: $cache = md5(serialize($_SERVER), TRUE);
49: }
50:
51: $s = '';
52: for ($i = 0; $i < $length; $i++) {
53: if ($i % 5 === 0) {
54: list($rand, $rand2) = explode(' ', microtime());
55: $rand += lcg_value();
56: }
57: $rand *= $chLen;
58: $s .= $charlist[($rand + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
59: $rand -= (int) $rand;
60: }
61: return $s;
62: }
63:
64: }
65: