Last active
September 27, 2017 15:47
-
-
Save jornane/59bcdfe973516982a5cf6fcecb32a9e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://blogs.msdn.microsoft.com/oldnewthing/20040315-00/?p=40253/ | |
function sid2bin($sid) { | |
if (!preg_match('/^S-(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(-[1-9][0-9]*){3,255}$/', $sid)) throw new Exception('Not an sid'); | |
$segments = explode('-', $sid); | |
$str = pack('hhnN', $segments[1], sizeof($segments)-3, $segments[2] >> 32, $segments[2]); | |
for($i=3;$i<sizeof($segments);$i++) { | |
$str .= pack('V', $segments[$i]); | |
} | |
return $str; | |
} | |
function bin2sid($bin) { | |
if (strlen($bin) % 4) throw new Exception('Not an sid'); | |
$authority = unpack('J', "\0\0" . substr($bin, 2, 6)); | |
$segments = ['S', ord($bin[0]), $authority[1]]; | |
for($i=8;$i<strlen($bin);$i+=4) { | |
$data = unpack('V', substr($bin, $i, $i+4)); | |
$segments[] = $data[1]; | |
} | |
if (ord($bin[1]) !== sizeof($segments)-3) throw new Exception('Not an sid'); | |
return implode('-', $segments); | |
} | |
function objectguid2bin($objectguid) { | |
if (!preg_match('/^[0-9a-z]{8}(-[0-9a-z]{4}){4}[0-9a-z]{8}$/i', $objectguid)) throw new Exception('Not an objectguid'); | |
$bin = hex2bin(str_replace('-', '', $objectguid)); | |
return reverseguid($bin); | |
} | |
function reverseguid($bin) { | |
return $bin{3} . $bin{2} . $bin{1} . $bin{0} | |
. $bin{5} . $bin{4} | |
. $bin{7} . $bin{6} | |
. substr($bin, 8); | |
} | |
function bin2objectguid($bin) { | |
if (strlen($bin) !== 16) throw new Exception('Not an objectguid'); | |
$bin = reverseguid($bin); | |
$segments = str_split(bin2hex($bin), 2); | |
$segments[3] .= '-'; | |
$segments[5] .= '-'; | |
$segments[7] .= '-'; | |
$segments[9] .= '-'; | |
return implode('', $segments); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment