Files
dn42-pingfinder/uuid.php
2016-07-26 22:56:10 +00:00

101 lines
2.8 KiB
PHP

<?php namespace UUID;
function v4()
{
$rand = bin2hex(random_bytes(16));
return sprintf(
'%08s-%04s-%04x-%04x-%012s',
substr($rand, 0, 8),
substr($rand, 8, 4),
(hexdec(substr($rand, 12, 4)) & 0x0fff) | 0x4000,
(hexdec(substr($rand, 16, 4)) & 0x3fff) | 0x8000,
substr($rand, 20, 12)
);
}
function v5($name, $namespace = '{00000000-0000-0000-0000-000000000000}')
{
if (!is_valid($namespace)) {
return false;
}
$nhex = str_replace(array('-', '{', '}'), '', $namespace);
$nstr = '';
for ($i = 0; $i < strlen($nhex); $i += 2) {
$nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1]));
}
$hash = sha1($nstr . $name);
return sprintf(
'%08s-%04s-%04x-%04x-%12s',
substr($hash, 0, 8),
substr($hash, 8, 4),
(hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,
(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
substr($hash, 20, 12)
);
}
function v6($node, $namespace = '{00000000-0000-0000-0000-000000000000}')
{
if (!is_valid($namespace)) return false;
$nhex = str_replace(array('-', '{', '}'), '', $namespace);
$nstr = '';
for ($i = 0; $i < strlen($nhex); $i += 2) {
$nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1]));
}
$name = sha1($nstr);
$node = sha1($nstr . $node);
date_default_timezone_set('UTC');
$year = dechex(date('Y') & 0x3fff | 0x8000);
list($usec, $sec) = explode(' ', microtime());
$sec = (int)$sec;
$epoch = mktime(0, 0, 0, 21, 12, 2012);
$usec = substr($usec, 2, 6);
$time = (string)($sec - $epoch) . $usec;
$tcode = substr(bcdechex(bcadd(bcmul($time, bcpow(2, 3)), mt_rand(0, 4))), 0, 12);
return strtolower(
sprintf(
"%08s-%04s-6%03s-%04s-%012s",
substr($name, 0, 8),
substr($node, 0, 4),
substr($node, 4, 3),
$year,
$tcode
)
);
}
function is_valid($uuid)
{
return preg_match(
'/^\{?[0-9a-f]{8}\-'
.'?[0-9a-f]{4}\-'
.'?[0-9a-f]{4}\-'
.'?[0-9a-f]{4}\-'
.'?[0-9a-f]{12}\}?$/i',
$uuid
) === 1;
}
function bcdechex($number) {
$hexvalues = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
$hexval = '';
while ($number != '0') {
$hexval = $hexvalues[bcmod($number, '16')] . $hexval;
$number = bcdiv($number, '16', 0);
}
return $hexval;
}