From 1a3f319a23aec6ee999029127dc468aa4163eb69 Mon Sep 17 00:00:00 2001 From: phpnut Date: Wed, 19 Dec 2007 09:23:26 +0000 Subject: [PATCH] "Refactoring String::uuid(); Adding fix when current PHP process ID is greater than 5 digits. If PHP process ID returns false or can not be determined a random 5 digit number will be generated. Added support for IPv6. String::uuid(); will default to crc32 of Security.salt if $node (IP) is 127.0.0.1, $node (IPv6) < 38 characters, or $node can not be determined." git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@6175 3807eeeb-6ff5-0310-8944-8be069107fe0 --- cake/libs/string.php | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/cake/libs/string.php b/cake/libs/string.php index bda87238d..a85db0065 100644 --- a/cake/libs/string.php +++ b/cake/libs/string.php @@ -85,26 +85,49 @@ class String extends Object { */ function uuid() { $node = env('SERVER_ADDR'); + $pid = null; - if(empty($node)) { + if (strpos($node, ':') !== false) { + if (substr_count($node, '::')) { + $node = str_replace('::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node); + } + $node = explode(':', $node) ; + $ipv6 = '' ; + + foreach ($node as $id) { + $ipv6 .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT); + } + $node = base_convert($ipv6, 2, 10); + + if (strlen($node) < 38) { + $node = null; + } else { + $node = crc32($node); + } + } elseif (empty($node)) { $host = env('HOSTNAME'); if (empty($host)) { $host = env('HOST'); } - if (empty($host)) { - $node = ip2long('127.0.0.1'); - } else { + if (!empty($host)) { $ip = gethostbyname($host); + if ($ip === $host) { $node = crc32($host); } else { $node = ip2long($ip); } } - } else { + } elseif ($node !== '127.0.0.1') { $node = ip2long($node); + } else { + $node = null; + } + + if (empty($node)) { + $node = crc32(Configure::read('Security.salt')); } if (function_exists('zend_thread_id')) { @@ -113,9 +136,14 @@ class String extends Object { $pid = getmypid(); } + if (!$pid) { + $pid = mt_rand(0, 0xfff) | 0x4000; + } + list($timeMid, $timeLow) = explode(' ', microtime()); $uuid = sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff, - mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node); + mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), substr($pid, 0, 5), $node); + return $uuid; } /**