Subversion Repositories uuid_mac_utils

Rev

Rev 34 | Rev 36 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 daniel-mar 1
<?php
2
 
3
/*
4
 * UUID utils for PHP
15 daniel-mar 5
 * Copyright 2011 - 2023 Daniel Marschall, ViaThinkSoft
34 daniel-mar 6
 * Version 2023-07-12
2 daniel-mar 7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
 
21
# This library requires either the GMP extension (or BCMath if gmp_supplement.inc.php is present)
22
 
23
if (file_exists(__DIR__ . '/mac_utils.inc.phps')) include_once __DIR__ . '/mac_utils.inc.phps'; // optionally used for uuid_info()
24
if (file_exists(__DIR__ . '/gmp_supplement.inc.php')) include_once __DIR__ . '/gmp_supplement.inc.php';
25
 
31 daniel-mar 26
const UUID_NAMEBASED_NS_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // FQDN
27
const UUID_NAMEBASED_NS_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
28
const UUID_NAMEBASED_NS_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
29
const UUID_NAMEBASED_NS_X500_DN = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; // DER according to https://github.com/cjsv/uuid/blob/master/Doc ?!
2 daniel-mar 30
 
24 daniel-mar 31
function _random_int($min, $max) {
32
        // This function tries a CSRNG and falls back to a RNG if no CSRNG is available
33
        try {
34
                return random_int($min, $max);
35
        } catch (Exception $e) {
36
                return mt_rand($min, $max);
37
        }
38
}
39
 
2 daniel-mar 40
function uuid_valid($uuid) {
41
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
42
        $uuid = strtoupper($uuid);
43
        #$uuid = trim($uuid);
44
 
45
        if (strlen($uuid) != 32) return false;
46
 
29 daniel-mar 47
        $uuid = preg_replace('@[0-9A-F]@i', '', $uuid);
2 daniel-mar 48
 
49
        return ($uuid == '');
50
}
51
 
28 daniel-mar 52
function uuid_info($uuid, $echo=true) {
2 daniel-mar 53
        if (!uuid_valid($uuid)) return false;
54
 
28 daniel-mar 55
        if (!$echo) ob_start();
56
 
2 daniel-mar 57
        #$uuid = trim($uuid);
58
        # $uuid = str_replace(array('-', '{', '}'), '', $uuid);
29 daniel-mar 59
        $uuid = strtolower($uuid);
60
        $uuid = preg_replace('@[^0-9A-F]@i', '', $uuid);
2 daniel-mar 61
 
62
        $x = hexdec(substr($uuid, 16, 1));
28 daniel-mar 63
             if ($x >= 14 /* 0b1110 */) $variant = 3;
64
        else if ($x >= 12 /* 0b110_ */) $variant = 2;
65
        else if ($x >=  8 /* 0b10__ */) $variant = 1;
66
        else if ($x >=  0 /* 0b0___ */) $variant = 0;
2 daniel-mar 67
        else $variant = -1; // should not happen
68
 
35 daniel-mar 69
        if ($uuid == '00000000000000000000000000000000') {
70
                echo sprintf("%-32s %s\n", "Special Use:", "Nil UUID");
71
                echo "\n";
72
        }
73
        else if ($uuid == 'ffffffffffffffffffffffffffffffff') {
74
                echo sprintf("%-32s %s\n", "Special Use:", "Max UUID");
75
                echo "\n";
76
        }
77
 
2 daniel-mar 78
        switch ($variant) {
79
                case 0:
33 daniel-mar 80
                        echo sprintf("%-32s %s\n", "Variant:", "[0b0__] Network Computing System (NCS)");
2 daniel-mar 81
 
82
                        /*
83
                         * Internal structure of variant #0 UUIDs
84
                         *
85
                         * The first 6 octets are the number of 4 usec units of time that have
86
                         * passed since 1/1/80 0000 GMT.  The next 2 octets are reserved for
87
                         * future use.  The next octet is an address family.  The next 7 octets
88
                         * are a host ID in the form allowed by the specified address family.
89
                         *
90
                         * Note that while the family field (octet 8) was originally conceived
91
                         * of as being able to hold values in the range [0..255], only [0..13]
92
                         * were ever used.  Thus, the 2 MSB of this field are always 0 and are
93
                         * used to distinguish old and current UUID forms.
94
                         */
95
 
28 daniel-mar 96
                        /*
97
                        Variant 0 UUID
98
                        - 32 bit High Time
99
                        - 16 bit Low Time
100
                        - 16 bit Reserved
29 daniel-mar 101
                        -  1 bit Variant (fix 0b0)
28 daniel-mar 102
                        -  7 bit Family
103
                        - 56 bit Node
104
                        */
105
 
2 daniel-mar 106
                        // Example of an UUID: 333a2276-0000-0000-0d00-00809c000000
107
 
35 daniel-mar 108
                        // TODO: also show legacy format, e.g. 458487b55160.02.c0.64.02.03.00.00.00
109
 
28 daniel-mar 110
                        # see also some notes at See https://github.com/cjsv/uuid/blob/master/Doc
2 daniel-mar 111
 
29 daniel-mar 112
                        /*
113
                        NOTE: A generator is not possible, because there are no timestamps left!
114
                        The last possible timestamp was:
30 daniel-mar 115
                            [0xFFFFFFFFFFFF] 2015-09-05 05:58:26'210655 GMT
29 daniel-mar 116
                        That is in the following UUID:
117
                            ffffffff-ffff-0000-027f-000001000000
118
                        Current timestamp generator:
119
                            echo dechex(round((microtime(true)+315532800)*250000));
120
                        */
27 daniel-mar 121
 
2 daniel-mar 122
                        # Timestamp: Count of 4us intervals since 01 Jan 1980 00:00:00 GMT
123
                        # 1/0,000004 = 250000
124
                        # Seconds between 1970 and 1980 : 315532800
125
                        # 250000*315532800=78883200000000
126
                        $timestamp = substr($uuid, 0, 12);
127
                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 128
                        $ts = gmp_add($ts, gmp_init("78883200000000", 10));
129
                        $ms = gmp_mod($ts, gmp_init("250000", 10));
130
                        $ts = gmp_div($ts, gmp_init("250000", 10));
131
                        $ts = gmp_strval($ts, 10);
132
                        $ms = gmp_strval($ms, 10);
133
                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 6/*us*/, '0', STR_PAD_LEFT).' GMT';
25 daniel-mar 134
                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
2 daniel-mar 135
 
136
                        $reserved = substr($uuid, 12, 4);
27 daniel-mar 137
                        echo sprintf("%-32s %s\n", "Reserved:", "[0x$reserved]");
2 daniel-mar 138
 
139
                        $family_hex = substr($uuid, 16, 2);
140
                        $family_dec = hexdec($family_hex);
28 daniel-mar 141
                        $nodeid_hex = substr($uuid, 18, 14);
142
                        $nodeid_dec = hexdec($nodeid_hex);
2 daniel-mar 143
                        if ($family_dec == 2) {
29 daniel-mar 144
                                $family_name = 'IP';
28 daniel-mar 145
                                // https://www.ibm.com/docs/en/aix/7.1?topic=u-uuid-gen-command-ncs (AIX 7.1) shows the following example output for /etc/ncs/uuid_gen -P
146
                                // := [
147
                                //    time_high := 16#458487df,
148
                                //    time_low := 16#9fb2,
149
                                //    reserved := 16#000,
150
                                //    family := chr(16#02),
151
                                //    host := [chr(16#c0), chr(16#64), chr(16#02), chr(16#03),
152
                                //             chr(16#00), chr(16#00), chr(16#00)]
153
                                //    ]
154
                                // This means that the IP address is 32 bits hex, and 32 bits are unused
155
                                $nodeid_desc = hexdec(substr($nodeid_hex,0,2)).'.'.
156
                                               hexdec(substr($nodeid_hex,2,2)).'.'.
157
                                               hexdec(substr($nodeid_hex,4,2)).'.'.
158
                                               hexdec(substr($nodeid_hex,6,2));
159
                                $rest = substr($nodeid_hex,8,6);
160
                                if ($rest != '000000') $nodeid_desc .= " + unexpected rest 0x$rest";
2 daniel-mar 161
                        } else if ($family_dec == 13) {
29 daniel-mar 162
                                $family_name = 'DDS (Data Link)';
28 daniel-mar 163
                                // https://www.ibm.com/docs/en/aix/7.1?topic=u-uuid-gen-command-ncs (AIX 7.1) shows the following example output for /etc/ncs/uuid_gen -C
164
                                // = { 0x34dc23af,
165
                                //    0xf000,
166
                                //    0x0000,
167
                                //    0x0d,
168
                                //    {0x00, 0x00, 0x7c, 0x5f, 0x00, 0x00, 0x00} };
169
                                // https://github.com/cjsv/uuid/blob/master/Doc writes:
170
                                //    "Family 13 (dds) looks like node is 00 | nnnnnn 000000."
171
 
172
                                $nodeid_desc = '';
173
 
174
                                $start = substr($nodeid_hex,0,2);
175
                                if ($start != '00') $nodeid_desc .= "unexpected start 0x$start + ";
176
 
177
                                $nodeid_desc .= ($nodeid_dec >> 24) & 0xFFFFFF;
178
 
179
                                $rest = substr($nodeid_hex,8,6);
180
                                if ($rest != '000000') $nodeid_desc .= " + unexpected rest 0x$rest";
2 daniel-mar 181
                        } else {
29 daniel-mar 182
                                $family_name = "Unknown (Family $family_dec)"; # There are probably no more families
183
                                $nodeid_desc = "Unknown";
2 daniel-mar 184
                        }
29 daniel-mar 185
                        echo sprintf("%-32s %s\n", "Family:", "[0x$family_hex] $family_name");
2 daniel-mar 186
 
28 daniel-mar 187
                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$nodeid_hex] $nodeid_desc");
2 daniel-mar 188
 
189
                        break;
190
                case 1:
35 daniel-mar 191
                        // TODO: Show byte order: 00112233-4455-6677-8899-aabbccddeeff => 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff
192
 
30 daniel-mar 193
                        $version = hexdec(substr($uuid, 12, 1));
2 daniel-mar 194
 
30 daniel-mar 195
                        if ($version <= 2) {
196
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 (Leach-Mealling-Salz) / DCE 1.1");
197
                        } else if (($version >= 3) && ($version <= 5)) {
198
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 (Leach-Mealling-Salz)");
199
                        } else if (($version >= 6) && ($version <= 8)) {
200
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122bis (Leach-Mealling-Peabody-Davis)");
201
                        } else {
202
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 ?");
203
                        }
204
 
2 daniel-mar 205
                        switch ($version) {
29 daniel-mar 206
                                case 6:
207
                                        /*
208
                                        Variant 1, Version 6 UUID
209
                                        - 48 bit High Time
210
                                        -  4 bit Version (fix 0x6)
211
                                        - 12 bit Low Time
212
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 213
                                        -  6 bit Clock Sequence High
214
                                        -  8 bit Clock Sequence Low
29 daniel-mar 215
                                        - 48 bit MAC Address
216
                                        */
31 daniel-mar 217
                                        echo sprintf("%-32s %s\n", "Version:", "[6] Reordered Time");
29 daniel-mar 218
                                        $uuid = substr($uuid,  0, 8).'-'.
219
                                                substr($uuid,  8, 4).'-'.
220
                                                substr($uuid, 12, 4).'-'.
221
                                                substr($uuid, 16, 4).'-'.
222
                                                substr($uuid, 20, 12);
223
                                        $uuid = uuid6_to_uuid1($uuid);
224
                                        $uuid = str_replace('-', '', $uuid);
225
 
226
                                /* fallthrough */
2 daniel-mar 227
                                case 1:
27 daniel-mar 228
                                        /*
229
                                        Variant 1, Version 1 UUID
230
                                        - 32 bit Low Time
231
                                        - 16 bit Mid Time
232
                                        -  4 bit Version (fix 0x1)
233
                                        - 12 bit High Time
28 daniel-mar 234
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 235
                                        -  6 bit Clock Sequence High
236
                                        -  8 bit Clock Sequence Low
27 daniel-mar 237
                                        - 48 bit MAC Address
238
                                        */
239
 
31 daniel-mar 240
                                        if ($version == 1) echo sprintf("%-32s %s\n", "Version:", "[1] Time-based with unique host identifier");
2 daniel-mar 241
 
242
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
243
                                        # 1/0,0000001 = 10000000
244
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).substr($uuid, 0, 8);
245
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 246
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
247
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
248
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
249
                                        $ts = gmp_strval($ts, 10);
250
                                        $ms = gmp_strval($ms, 10);
251
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7/*0.1us*/, '0', STR_PAD_LEFT).' GMT';
25 daniel-mar 252
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
2 daniel-mar 253
 
254
                                        $x = hexdec(substr($uuid, 16, 4));
255
                                        $dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
256
                                        $hex = substr($uuid, 16, 4);
25 daniel-mar 257
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 258
 
259
                                        $x = substr($uuid, 20, 12);
260
                                        $nodeid = '';
261
                                        for ($i=0; $i<6; $i++) {
262
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 263
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 264
                                        }
30 daniel-mar 265
                                        $nodeid = strtoupper($nodeid);
27 daniel-mar 266
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 267
 
268
                                        if (function_exists('decode_mac')) {
25 daniel-mar 269
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
29 daniel-mar 270
                                                decode_mac(strtoupper($nodeid));
2 daniel-mar 271
                                        }
272
 
273
                                        break;
274
                                case 2:
27 daniel-mar 275
                                        /*
276
                                        Variant 1, Version 2 UUID
277
                                        - 32 bit Local Domain Number
278
                                        - 16 bit Mid Time
279
                                        -  4 bit Version (fix 0x2)
280
                                        - 12 bit High Time
28 daniel-mar 281
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 282
                                        -  6 bit Clock Sequence
28 daniel-mar 283
                                        -  8 bit Local Domain
27 daniel-mar 284
                                        - 48 bit MAC Address
285
                                        */
286
 
28 daniel-mar 287
                                        // see also https://unicorn-utterances.com/posts/what-happened-to-uuid-v2
288
 
25 daniel-mar 289
                                        echo sprintf("%-32s %s\n", "Version:", "[2] DCE Security version");
2 daniel-mar 290
 
27 daniel-mar 291
                                        # The clock_seq_low field (which represents an integer in the range [0, 28-1]) is interpreted as a local domain (as represented by sec_rgy_domain_t; see sec_rgy_domain_t ); that is, an identifier domain meaningful to the local host. (Note that the data type sec_rgy_domain_t can potentially hold values outside the range [0, 28-1]; however, the only values currently registered are in the range [0, 2], so this type mismatch is not significant.) In the particular case of a POSIX host, the value sec_rgy_domain_person is to be interpreted as the "POSIX UID domain", and the value sec_rgy_domain_group is to be interpreted as the "POSIX GID domain".
292
                                        $x = substr($uuid, 18, 2);
293
                                        if ($x == '00') $domain_info = 'Person (POSIX: User-ID)';
294
                                        else if ($x == '01') $domain_info = 'Group (POSIX: Group-ID)';
295
                                        else if ($x == '02') $domain_info = 'Organization';
296
                                        else $domain_info = 'site-defined (Domain '.hexdec($x).')';
297
                                        echo sprintf("%-32s %s\n", "Local Domain:", "[0x$x] $domain_info");
298
 
2 daniel-mar 299
                                        # The time_low field (which represents an integer in the range [0, 232-1]) is interpreted as a local-ID; that is, an identifier (within the domain specified by clock_seq_low) meaningful to the local host. In the particular case of a POSIX host, when combined with a POSIX UID or POSIX GID domain in the clock_seq_low field (above), the time_low field represents a POSIX UID or POSIX GID, respectively.
300
                                        $x = substr($uuid, 0, 8);
29 daniel-mar 301
                                        $dec = hexdec($x);
302
                                        echo sprintf("%-32s %s\n", "Local Domain Number:", "[0x$x] $dec");
2 daniel-mar 303
 
304
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
305
                                        # 1/0,0000001 = 10000000
306
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'00000000';
307
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 308
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
309
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
310
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
311
                                        $ts = gmp_strval($ts, 10);
312
                                        $ms = gmp_strval($ms, 10);
313
                                        $ts_min = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7/*0.1us*/, '0', STR_PAD_LEFT).' GMT';
2 daniel-mar 314
 
315
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'FFFFFFFF';
316
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 317
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
318
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
319
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
320
                                        $ts = gmp_strval($ts, 10);
321
                                        $ms = gmp_strval($ms, 10);
322
                                        $ts_max = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7/*0.1us*/, '0', STR_PAD_LEFT).' GMT';
2 daniel-mar 323
 
29 daniel-mar 324
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4)/*.'xxxxxxxx'*/;
25 daniel-mar 325
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts_min - $ts_max");
2 daniel-mar 326
 
28 daniel-mar 327
                                        $x = hexdec(substr($uuid, 16, 2));
328
                                        $dec = $x & 0x3F; // The highest 2 bits are used by "variant" (10xx)
329
                                        $hex = substr($uuid, 16, 2);
27 daniel-mar 330
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 331
 
332
                                        $x = substr($uuid, 20, 12);
333
                                        $nodeid = '';
334
                                        for ($i=0; $i<6; $i++) {
335
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 336
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 337
                                        }
30 daniel-mar 338
                                        $nodeid = strtoupper($nodeid);
27 daniel-mar 339
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 340
 
341
                                        if (function_exists('decode_mac')) {
25 daniel-mar 342
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
29 daniel-mar 343
                                                decode_mac(strtoupper($nodeid));
2 daniel-mar 344
                                        }
345
 
346
                                        break;
347
                                case 3:
28 daniel-mar 348
                                        /*
349
                                        Variant 1, Version 3 UUID
350
                                        - 48 bit Hash High
29 daniel-mar 351
                                        -  4 bit Version (fix 0x3)
28 daniel-mar 352
                                        - 12 bit Hash Mid
353
                                        -  2 bit Variant (fix 0b10)
354
                                        - 62 bit Hash Low
355
                                        */
356
 
25 daniel-mar 357
                                        echo sprintf("%-32s %s\n", "Version:", "[3] Name-based (MD5 hash)");
2 daniel-mar 358
 
359
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 360
 
2 daniel-mar 361
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 362
 
32 daniel-mar 363
                                        $var16a = strtoupper(dechex((hexdec($hash[16])&3) + 0x0/*00__*/));
364
                                        $var16b = strtoupper(dechex((hexdec($hash[16])&3) + 0x4/*01__*/));
365
                                        $var16c = strtoupper(dechex((hexdec($hash[16])&3) + 0x8/*10__*/));
366
                                        $var16d = strtoupper(dechex((hexdec($hash[16])&3) + 0xC/*11__*/));
2 daniel-mar 367
                                        $hash[16] = '?'; // was partially overwritten by variant
368
 
27 daniel-mar 369
                                        echo sprintf("%-32s %s\n", "MD5(Namespace+Subject):", "[0x$hash]");
370
                                        echo sprintf("%-32s %s\n", "", "                   ^");
371
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 372
 
373
                                        break;
374
                                case 4:
28 daniel-mar 375
                                        /*
376
                                        Variant 1, Version 4 UUID
377
                                        - 48 bit Random High
29 daniel-mar 378
                                        -  4 bit Version (fix 0x4)
28 daniel-mar 379
                                        - 12 bit Random Mid
380
                                        -  2 bit Variant (fix 0b10)
381
                                        - 62 bit Random Low
382
                                        */
383
 
25 daniel-mar 384
                                        echo sprintf("%-32s %s\n", "Version:", "[4] Random");
2 daniel-mar 385
 
25 daniel-mar 386
                                        $rand_line1 = '';
387
                                        $rand_line2 = '';
2 daniel-mar 388
                                        for ($i=0; $i<16; $i++) {
389
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
390
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
391
 
392
                                                if ($i == 6) {
25 daniel-mar 393
                                                        // was overwritten by version
394
                                                        $bin[0] = '?';
395
                                                        $bin[1] = '?';
396
                                                        $bin[2] = '?';
397
                                                        $bin[3] = '?';
2 daniel-mar 398
                                                } else if ($i == 8) {
25 daniel-mar 399
                                                        // was partially overwritten by variant
400
                                                        $bin[0] = '?';
401
                                                        $bin[1] = '?';
2 daniel-mar 402
                                                }
403
 
25 daniel-mar 404
                                                if ($i<8) $rand_line1 .= "$bin ";
405
                                                if ($i>=8) $rand_line2 .= "$bin ";
2 daniel-mar 406
                                        }
25 daniel-mar 407
                                        echo sprintf("%-32s %s\n", "Random bits:", trim($rand_line1));
408
                                        echo sprintf("%-32s %s\n", "",             trim($rand_line2));
2 daniel-mar 409
 
27 daniel-mar 410
                                        $rand_bytes = str_replace('-', '', strtolower($uuid));
411
                                        $rand_bytes[12] = '?'; // was overwritten by version
32 daniel-mar 412
                                        $var16a = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x0/*00__*/));
413
                                        $var16b = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x4/*01__*/));
414
                                        $var16c = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x8/*10__*/));
415
                                        $var16d = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0xC/*11__*/));
27 daniel-mar 416
                                        $rand_bytes[16] = '?'; // was partially overwritten by variant
417
                                        echo sprintf("%-32s %s\n", "Random bytes:", "[0x$rand_bytes]");
418
                                        echo sprintf("%-32s %s\n", "", "                   ^");
419
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
420
 
2 daniel-mar 421
                                        break;
422
                                case 5:
28 daniel-mar 423
                                        /*
424
                                        Variant 1, Version 5 UUID
425
                                        - 48 bit Hash High
29 daniel-mar 426
                                        -  4 bit Version (fix 0x5)
28 daniel-mar 427
                                        - 12 bit Hash Mid
428
                                        -  2 bit Variant (fix 0b10)
429
                                        - 62 bit Hash Low
430
                                        */
431
 
25 daniel-mar 432
                                        echo sprintf("%-32s %s\n", "Version:", "[5] Name-based (SHA-1 hash)");
2 daniel-mar 433
 
434
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 435
 
2 daniel-mar 436
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 437
 
32 daniel-mar 438
                                        $var16a = strtoupper(dechex((hexdec($hash[16])&3) + 0x0/*00__*/));
439
                                        $var16b = strtoupper(dechex((hexdec($hash[16])&3) + 0x4/*01__*/));
440
                                        $var16c = strtoupper(dechex((hexdec($hash[16])&3) + 0x8/*10__*/));
441
                                        $var16d = strtoupper(dechex((hexdec($hash[16])&3) + 0xC/*11__*/));
2 daniel-mar 442
                                        $hash[16] = '?'; // was partially overwritten by variant
27 daniel-mar 443
 
2 daniel-mar 444
                                        $hash .= '????????'; // was cut off
445
 
27 daniel-mar 446
                                        echo sprintf("%-32s %s\n", "SHA1(Namespace+Subject):", "[0x$hash]");
447
                                        echo sprintf("%-32s %s\n", "", "                   ^");
448
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 449
 
450
                                        break;
27 daniel-mar 451
                                case 7:
29 daniel-mar 452
                                        /*
453
                                        Variant 1, Version 7 UUID
454
                                        - 48 bit Unix Time in milliseconds
455
                                        -  4 bit Version (fix 0x7)
456
                                        - 12 bit Random
457
                                        -  2 bit Variant (fix 0b10)
458
                                        - 62 bit Random
459
                                        */
460
 
31 daniel-mar 461
                                        echo sprintf("%-32s %s\n", "Version:", "[7] Unix Epoch Time");
29 daniel-mar 462
 
463
                                        $timestamp = substr($uuid, 0, 12);
30 daniel-mar 464
 
465
                                        // Timestamp: Split into seconds and milliseconds
29 daniel-mar 466
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 467
                                        $ms = gmp_mod($ts, gmp_init("1000", 10));
468
                                        $ts = gmp_div($ts, gmp_init("1000", 10));
469
                                        $ts = gmp_strval($ts, 10);
470
                                        $ms = gmp_strval($ms, 10);
471
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 3/*ms*/, '0', STR_PAD_LEFT).' GMT';
29 daniel-mar 472
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
473
 
474
                                        $rand = '';
475
                                        for ($i=6; $i<16; $i++) {
476
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
477
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
478
 
479
                                                if ($i == 6) {
480
                                                        // was overwritten by version
481
                                                        $bin[0] = '?';
482
                                                        $bin[1] = '?';
483
                                                        $bin[2] = '?';
484
                                                        $bin[3] = '?';
485
                                                } else if ($i == 8) {
486
                                                        // was partially overwritten by variant
487
                                                        $bin[0] = '?';
488
                                                        $bin[1] = '?';
489
                                                }
490
 
491
                                                $rand .= "$bin ";
492
                                        }
493
                                        echo sprintf("%-32s %s\n", "Random bits:", trim($rand));
494
 
495
                                        $rand_bytes = substr(str_replace('-', '', strtolower($uuid)),13);
32 daniel-mar 496
                                        $var16a = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x0/*00__*/));
497
                                        $var16b = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x4/*01__*/));
498
                                        $var16c = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x8/*10__*/));
499
                                        $var16d = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0xC/*11__*/));
29 daniel-mar 500
                                        $rand_bytes[3] = '?'; // was partially overwritten by variant
501
                                        echo sprintf("%-32s %s\n", "Random bytes:", "[0x$rand_bytes]");
502
                                        echo sprintf("%-32s %s\n", "", "      ^");
503
                                        echo sprintf("%-32s %s\n", "", "      $var16a, $var16b, $var16c, or $var16d");
504
 
505
                                        // TODO: convert to and from Base32 CROCKFORD ULID (make 2 methods in uuid_utils.inc.php)
506
                                        // e.g. ULID: 01GCZ05N3JFRKBRWKNGCQZGP44
507
                                        // "Be aware that all version 7 UUIDs may be converted to ULIDs but not all ULIDs may be converted to UUIDs."
508
 
27 daniel-mar 509
                                        break;
510
                                case 8:
29 daniel-mar 511
                                        /*
512
                                        Variant 1, Version 8 UUID
35 daniel-mar 513
                                        - 48 bit Custom data
29 daniel-mar 514
                                        -  4 bit Version (fix 0x8)
35 daniel-mar 515
                                        - 12 bit Custom data
29 daniel-mar 516
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 517
                                        - 62 bit Custom data
29 daniel-mar 518
                                        */
519
 
31 daniel-mar 520
                                        echo sprintf("%-32s %s\n", "Version:", "[8] Custom implementation");
29 daniel-mar 521
 
522
                                        $custom_data = substr($uuid,0,12).substr($uuid,13); // exclude version nibble
523
                                        $custom_data[15] = dechex(hexdec($custom_data[15])&3); // nibble was partially overwritten by variant
524
                                        $custom_data = strtolower($custom_data);
525
 
34 daniel-mar 526
                                        $custom_block1 = substr($uuid,  0, 8);
527
                                        $custom_block2 = substr($uuid,  8, 4);
528
                                        $custom_block3 = substr($uuid, 12, 4);
529
                                        $custom_block4 = substr($uuid, 16, 4);
530
                                        $custom_block5 = substr($uuid, 20);
531
 
532
                                        $custom_block3 = substr($custom_block3, 1); // remove version
533
                                        $custom_block4[0] = dechex(hexdec($custom_block4[0])&3); // remove variant
534
 
29 daniel-mar 535
                                        echo sprintf("%-32s %s\n", "Custom data:", "[0x$custom_data]");
34 daniel-mar 536
                                        echo sprintf("%-32s %s\n", "Custom block1 (32 bit):", "[0x$custom_block1]");
537
                                        echo sprintf("%-32s %s\n", "Custom block2 (16 bit):", "[0x$custom_block2]");
538
                                        echo sprintf("%-32s %s\n", "Custom block3 (12 bit):", "[0x$custom_block3]");
539
                                        echo sprintf("%-32s %s\n", "Custom block4 (14 bit):", "[0x$custom_block4]");
540
                                        echo sprintf("%-32s %s\n", "Custom block5 (48 bit):", "[0x$custom_block5]");
29 daniel-mar 541
 
27 daniel-mar 542
                                        break;
2 daniel-mar 543
                                default:
25 daniel-mar 544
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Unknown");
2 daniel-mar 545
                                        break;
546
                        }
547
 
548
                        break;
549
                case 2:
35 daniel-mar 550
                        // TODO: Show byte order: 00112233-4455-6677-8899-aabbccddeeff => 33 22 11 00 55 44 77 66 88 99 aa bb cc dd ee ff
551
 
31 daniel-mar 552
                        // TODO: Is there any scheme in that legacy Microsoft GUIDs?
27 daniel-mar 553
                        echo sprintf("%-32s %s\n", "Variant:", "[0b110] Reserved for Microsoft Corporation");
2 daniel-mar 554
                        break;
555
                case 3:
27 daniel-mar 556
                        echo sprintf("%-32s %s\n", "Variant:", "[0b111] Reserved for future use");
2 daniel-mar 557
                        break;
558
        }
28 daniel-mar 559
 
560
        if (!$echo) {
561
                $out = ob_get_contents();
562
                ob_end_clean();
563
                return $out;
31 daniel-mar 564
        } else {
565
                return true;
28 daniel-mar 566
        }
2 daniel-mar 567
}
568
 
569
function uuid_canonize($uuid) {
570
        if (!uuid_valid($uuid)) return false;
571
        return oid_to_uuid(uuid_to_oid($uuid));
572
}
573
 
574
function oid_to_uuid($oid) {
575
        if (!is_uuid_oid($oid)) return false;
576
 
8 daniel-mar 577
        if (substr($oid,0,1) == '.') {
2 daniel-mar 578
                $oid = substr($oid, 1);
579
        }
580
        $ary = explode('.', $oid);
581
 
582
        if (!isset($ary[2])) return false;
583
 
584
        $val = $ary[2];
585
 
586
        $x = gmp_init($val, 10);
587
        $y = gmp_strval($x, 16);
588
        $y = str_pad($y, 32, "0", STR_PAD_LEFT);
589
        return substr($y,  0, 8).'-'.
590
               substr($y,  8, 4).'-'.
591
               substr($y, 12, 4).'-'.
592
               substr($y, 16, 4).'-'.
593
               substr($y, 20, 12);
594
}
595
 
596
function is_uuid_oid($oid, $only_allow_root=false) {
9 daniel-mar 597
        if (substr($oid,0,1) == '.') $oid = substr($oid, 1); // remove leading dot
2 daniel-mar 598
 
599
        $ary = explode('.', $oid);
600
 
601
        if ($only_allow_root) {
602
                if (count($ary) != 3) return false;
603
        } else {
604
                if (count($ary) < 3) return false;
605
        }
606
 
607
        if ($ary[0] != '2') return false;
608
        if ($ary[1] != '25') return false;
609
        for ($i=2; $i<count($ary); $i++) {
610
                $v = $ary[$i];
611
                if (!is_numeric($v)) return false;
612
                if ($i == 2) {
613
                        // Must be in the range of 128 bit UUID
614
                        $test = gmp_init($v, 10);
615
                        if (strlen(gmp_strval($test, 16)) > 32) return false;
616
                }
617
                if ($v < 0) return false;
618
        }
619
 
620
        return true;
621
}
622
 
623
function uuid_to_oid($uuid) {
624
        if (!uuid_valid($uuid)) return false;
625
 
626
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
627
        $x = gmp_init($uuid, 16);
29 daniel-mar 628
        return '2.25.'.gmp_strval($x, 10);
2 daniel-mar 629
}
630
 
31 daniel-mar 631
function uuid_numeric_value($uuid) {
632
        $oid = uuid_to_oid($uuid);
633
        if (!$oid) return false;
634
        return substr($oid, strlen('2.25.'));
635
}
636
 
637
function uuid_c_syntax($uuid) {
638
        $uuid = str_replace('{', '', $uuid);
639
        return '{ 0x' . substr($uuid, 0, 8) .
640
                ', 0x' . substr($uuid, 9, 4) .
641
                ', 0x' . substr($uuid, 14, 4) .
642
                ', { 0x' . substr($uuid, 19, 2).
643
                ', 0x' . substr($uuid, 21, 2) .
644
                ', 0x' . substr($uuid, 24, 2) .
645
                ', 0x' . substr($uuid, 26, 2) .
646
                ', 0x' . substr($uuid, 28, 2) .
647
                ', 0x' . substr($uuid, 30, 2) .
648
                ', 0x' . substr($uuid, 32, 2) .
649
                ', 0x' . substr($uuid, 34, 2) . ' } }';
650
}
651
 
30 daniel-mar 652
function gen_uuid($prefer_mac_address_based = true) {
653
        $uuid = $prefer_mac_address_based ? gen_uuid_reordered()/*UUIDv6*/ : false;
654
        if ($uuid === false) $uuid = gen_uuid_unix_epoch()/*UUIDv7*/;
2 daniel-mar 655
        return $uuid;
656
}
657
 
30 daniel-mar 658
# --------------------------------------
659
// Variant 1, Version 1 (Time based) UUID
660
# --------------------------------------
28 daniel-mar 661
 
30 daniel-mar 662
function gen_uuid_v1() {
663
        return gen_uuid_timebased();
664
}
2 daniel-mar 665
function gen_uuid_timebased() {
666
        # On Debian: apt-get install php-uuid
667
        # extension_loaded('uuid')
668
        if (function_exists('uuid_create')) {
669
                # OSSP uuid extension like seen in php5-uuid at Debian 8
670
                /*
671
                $x = uuid_create($context);
672
                uuid_make($context, UUID_MAKE_V1);
673
                uuid_export($context, UUID_FMT_STR, $uuid);
674
                return trim($uuid);
675
                */
676
 
677
                # PECL uuid extension like seen in php-uuid at Debian 9
678
                return trim(uuid_create(UUID_TYPE_TIME));
679
        }
680
 
681
        # On Debian: apt-get install uuid-runtime
682
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
683
                $out = array();
684
                $ec = -1;
685
                exec('uuidgen -t 2>/dev/null', $out, $ec);
686
                if ($ec == 0) return trim($out[0]);
687
        }
688
 
689
        # If we hadn't any success yet, then implement the time based generation routine ourselves!
690
        # Based on https://github.com/fredriklindberg/class.uuid.php/blob/master/class.uuid.php
691
 
692
        $uuid = array(
693
                'time_low' => 0,                /* 32-bit */
694
                'time_mid' => 0,                /* 16-bit */
695
                'time_hi' => 0,                 /* 16-bit */
696
                'clock_seq_hi' => 0,            /*  8-bit */
697
                'clock_seq_low' => 0,           /*  8-bit */
698
                'node' => array()               /* 48-bit */
699
        );
700
 
701
        /*
702
         * Get current time in 100 ns intervals. The magic value
703
         * is the offset between UNIX epoch and the UUID UTC
704
         * time base October 15, 1582.
705
         */
29 daniel-mar 706
        usleep(1); // make sure the timestamp is not used before
2 daniel-mar 707
        $tp = gettimeofday();
708
        $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) + 0x01B21DD213814000;
709
 
710
        $uuid['time_low'] = $time & 0xffffffff;
711
        /* Work around PHP 32-bit bit-operation limits */
712
        $high = intval($time / 0xffffffff);
713
        $uuid['time_mid'] = $high & 0xffff;
714
        $uuid['time_hi'] = (($high >> 16) & 0xfff) | (1/*TimeBased*/ << 12);
715
 
716
        /*
717
         * We don't support saved state information and generate
718
         * a random clock sequence each time.
719
         */
24 daniel-mar 720
        $uuid['clock_seq_hi'] = 0x80 | _random_int(0, 64);
721
        $uuid['clock_seq_low'] = _random_int(0, 255);
2 daniel-mar 722
 
723
        /*
724
         * Node should be set to the 48-bit IEEE node identifier
725
         */
726
        $mac = get_mac_address();
727
        if ($mac) {
25 daniel-mar 728
                $node = str_replace('-','',str_replace(':','',$mac));
2 daniel-mar 729
                for ($i = 0; $i < 6; $i++) {
730
                        $uuid['node'][$i] = hexdec(substr($node, $i*2, 2));
731
                }
732
 
733
                /*
734
                 * Now output the UUID
735
                 */
736
                return sprintf(
737
                        '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
738
                        ($uuid['time_low']), ($uuid['time_mid']), ($uuid['time_hi']),
739
                        $uuid['clock_seq_hi'], $uuid['clock_seq_low'],
740
                        $uuid['node'][0], $uuid['node'][1], $uuid['node'][2],
741
                        $uuid['node'][3], $uuid['node'][4], $uuid['node'][5]);
742
        }
743
 
744
        # We cannot generate the timebased UUID!
745
        return false;
746
}
747
function get_mac_address() {
748
        static $detected_mac = false;
749
 
750
        if ($detected_mac !== false) { // false NOT null!
751
                return $detected_mac;
752
        }
753
 
754
        // TODO: This should actually be part of mac_utils.inc.php, but we need it
755
        //       here, and mac_utils.inc.php shall only be optional. What to do?
756
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
757
                // Windows
758
                $cmds = array(
759
                        "ipconfig /all", // faster
760
                        "getmac"
761
                );
762
                foreach ($cmds as $cmd) {
763
                        $out = array();
764
                        $ec = -1;
765
                        exec($cmd, $out, $ec);
766
                        if ($ec == 0) {
767
                                $out = implode("\n",$out);
768
                                $m = array();
31 daniel-mar 769
                                if (preg_match("/([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})/ismU", $out, $m)) {
25 daniel-mar 770
                                        $detected_mac = strtolower($m[1]);
2 daniel-mar 771
                                        return $detected_mac;
772
                                }
773
                        }
774
                }
775
        } else if (strtoupper(PHP_OS) == 'DARWIN') {
776
                // Mac OS X
777
                $cmds = array(
778
                        "networksetup -listallhardwareports 2>/dev/null",
779
                        "netstat -i 2>/dev/null"
780
                );
781
                foreach ($cmds as $cmd) {
782
                        $out = array();
783
                        $ec = -1;
784
                        exec($cmd, $out, $ec);
785
                        if ($ec == 0) {
786
                                $out = implode("\n",$out);
787
                                $m = array();
788
                                if (preg_match("/([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/ismU", $out, $m)) {
789
                                        $detected_mac = $m[1];
790
                                        return $detected_mac;
791
                                }
792
                        }
793
                }
794
        } else {
795
                // Linux
8 daniel-mar 796
                $addresses = @glob('/sys/class/net/'.'*'.'/address');
797
                foreach ($addresses as $x) {
2 daniel-mar 798
                        if (!strstr($x,'/lo/')) {
799
                                $detected_mac = trim(file_get_contents($x));
800
                                return $detected_mac;
801
                        }
802
                }
803
                $cmds = array(
804
                        "netstat -ie 2>/dev/null",
805
                        "ifconfig 2>/dev/null" // only available for root (because it is in sbin)
806
                );
807
                foreach ($cmds as $cmd) {
808
                        $out = array();
809
                        $ec = -1;
810
                        exec($cmd, $out, $ec);
811
                        if ($ec == 0) {
812
                                $out = implode("\n",$out);
813
                                $m = array();
814
                                if (preg_match("/([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/ismU", $out, $m)) {
815
                                        $detected_mac = $m[1];
816
                                        return $detected_mac;
817
                                }
818
                        }
819
                }
820
        }
821
 
822
        $detected_mac = null;
823
        return $detected_mac;
824
}
825
 
30 daniel-mar 826
# --------------------------------------
28 daniel-mar 827
// Variant 1, Version 2 (DCE Security) UUID
30 daniel-mar 828
# --------------------------------------
829
 
27 daniel-mar 830
define('DCE_DOMAIN_PERSON', 0);
831
define('DCE_DOMAIN_GROUP', 1);
832
define('DCE_DOMAIN_ORG', 2);
30 daniel-mar 833
function gen_uuid_v2($domain, $id) {
834
        return gen_uuid_dce($domain, $id);
835
}
2 daniel-mar 836
function gen_uuid_dce($domain, $id) {
31 daniel-mar 837
        if (($domain ?? '') === '') throw new Exception("Domain ID missing");
838
        if (!is_numeric($domain)) throw new Exception("Invalid Domain ID");
839
        if (($domain < 0) || ($domain > 255)) throw new Exception("Domain ID must be in range 0..255");
840
 
841
        if (($id ?? '') === '') throw new Exception("ID value missing");
842
        if (!is_numeric($id)) throw new Exception("Invalid ID value");
843
        if (($id < 0) || ($id > 4294967295)) throw new Exception("ID value must be in range 0..4294967295");
844
 
2 daniel-mar 845
        # Start with a version 1 UUID
846
        $uuid = gen_uuid_timebased();
847
 
27 daniel-mar 848
        # Add Domain Number
2 daniel-mar 849
        $uuid = str_pad(dechex($id), 8, '0', STR_PAD_LEFT) . substr($uuid, 8);
850
 
27 daniel-mar 851
        # Add Domain (this overwrites part of the clock sequence)
2 daniel-mar 852
        $uuid = substr($uuid,0,21) . str_pad(dechex($domain), 2, '0', STR_PAD_LEFT) . substr($uuid, 23);
853
 
854
        # Change version to 2
855
        $uuid[14] = '2';
856
 
857
        return $uuid;
858
}
859
 
30 daniel-mar 860
# --------------------------------------
28 daniel-mar 861
// Variant 1, Version 3 (MD5 name based) UUID
30 daniel-mar 862
# --------------------------------------
863
 
864
function gen_uuid_v3($namespace_uuid, $name) {
865
        return gen_uuid_md5_namebased($namespace_uuid, $name);
866
}
2 daniel-mar 867
function gen_uuid_md5_namebased($namespace_uuid, $name) {
31 daniel-mar 868
        if (($namespace_uuid ?? '') === '') throw new Exception("Namespace UUID missing");
869
        if (!uuid_valid($namespace_uuid)) throw new Exception("Invalid namespace UUID '$namespace_uuid'");
870
 
2 daniel-mar 871
        $namespace_uuid = uuid_canonize($namespace_uuid);
872
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
873
        $namespace_uuid = hex2bin($namespace_uuid);
874
 
875
        $hash = md5($namespace_uuid.$name);
876
        $hash[12] = '3'; // Set version: 3 = MD5
877
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
878
 
879
        return substr($hash,  0, 8).'-'.
880
               substr($hash,  8, 4).'-'.
881
               substr($hash, 12, 4).'-'.
882
               substr($hash, 16, 4).'-'.
883
               substr($hash, 20, 12);
884
}
885
 
30 daniel-mar 886
# --------------------------------------
28 daniel-mar 887
// Variant 1, Version 4 (Random) UUID
30 daniel-mar 888
# --------------------------------------
889
 
890
function gen_uuid_v4() {
891
        return gen_uuid_random();
892
}
2 daniel-mar 893
function gen_uuid_random() {
894
        # On Windows: Requires
895
        #    extension_dir = "C:\php-8.0.3-nts-Win32-vs16-x64\ext"
896
        #    extension=com_dotnet
31 daniel-mar 897
        // TODO: can we trust that com_create_guid() always outputs UUIDv4?
30 daniel-mar 898
        /*
2 daniel-mar 899
        if (function_exists('com_create_guid')) {
900
                return strtolower(trim(com_create_guid(), '{}'));
901
        }
30 daniel-mar 902
        */
2 daniel-mar 903
 
904
        # On Debian: apt-get install php-uuid
905
        # extension_loaded('uuid')
906
        if (function_exists('uuid_create')) {
907
                # OSSP uuid extension like seen in php5-uuid at Debian 8
908
                /*
909
                $x = uuid_create($context);
910
                uuid_make($context, UUID_MAKE_V4);
911
                uuid_export($context, UUID_FMT_STR, $uuid);
912
                return trim($uuid);
913
                */
914
 
915
                # PECL uuid extension like seen in php-uuid at Debian 9
916
                return trim(uuid_create(UUID_TYPE_RANDOM));
917
        }
918
 
919
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
920
                # On Debian: apt-get install uuid-runtime
921
                $out = array();
922
                $ec = -1;
923
                exec('uuidgen -r 2>/dev/null', $out, $ec);
924
                if ($ec == 0) return trim($out[0]);
925
 
926
                # On Debian Jessie: UUID V4 (Random)
927
                if (file_exists('/proc/sys/kernel/random/uuid')) {
928
                        return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
929
                }
930
        }
931
 
932
        # Make the UUID by ourselves
933
        # Source: http://rogerstringer.com/2013/11/15/generate-uuids-php
934
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
24 daniel-mar 935
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ),
936
                _random_int( 0, 0xffff ),
937
                _random_int( 0, 0x0fff ) | 0x4000,
938
                _random_int( 0, 0x3fff ) | 0x8000,
939
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ), _random_int( 0, 0xffff )
2 daniel-mar 940
        );
941
}
942
 
30 daniel-mar 943
# --------------------------------------
28 daniel-mar 944
// Variant 1, Version 5 (SHA1 name based) UUID
30 daniel-mar 945
# --------------------------------------
946
 
947
function gen_uuid_v5($namespace_uuid, $name) {
948
        return gen_uuid_sha1_namebased($namespace_uuid, $name);
949
}
2 daniel-mar 950
function gen_uuid_sha1_namebased($namespace_uuid, $name) {
31 daniel-mar 951
        if (($namespace_uuid ?? '') === '') throw new Exception("Namespace UUID missing");
952
        if (!uuid_valid($namespace_uuid)) throw new Exception("Invalid namespace UUID '$namespace_uuid'");
953
 
2 daniel-mar 954
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
955
        $namespace_uuid = hex2bin($namespace_uuid);
956
 
957
        $hash = sha1($namespace_uuid.$name);
958
        $hash[12] = '5'; // Set version: 5 = SHA1
27 daniel-mar 959
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "0b10__" (RFC4122/DCE1.1)
2 daniel-mar 960
 
961
        return substr($hash,  0, 8).'-'.
962
               substr($hash,  8, 4).'-'.
963
               substr($hash, 12, 4).'-'.
964
               substr($hash, 16, 4).'-'.
965
               substr($hash, 20, 12);
966
}
967
 
30 daniel-mar 968
# --------------------------------------
969
// Variant 1, Version 6 (Reordered) UUID
970
# --------------------------------------
971
 
972
function gen_uuid_v6() {
973
        return gen_uuid_reordered();
974
}
975
function gen_uuid_reordered() {
976
        // Start with a UUIDv1
977
        $uuid = gen_uuid_timebased();
978
 
979
        // Convert to UUIDv6
980
        return uuid1_to_uuid6($uuid);
981
}
982
function uuid6_to_uuid1($hex) {
983
        $hex = uuid_canonize($hex);
984
        if ($hex === false) return false;
985
        $hex = preg_replace('@[^0-9A-F]@i', '', $hex);
986
        $hex = substr($hex, 7, 5).
987
               substr($hex, 13, 3).
988
               substr($hex, 3, 4).
989
               '1' . substr($hex, 0, 3).
990
               substr($hex, 16);
991
        return substr($hex,  0, 8).'-'.
992
               substr($hex,  8, 4).'-'.
993
               substr($hex, 12, 4).'-'.
994
               substr($hex, 16, 4).'-'.
995
               substr($hex, 20, 12);
996
}
997
function uuid1_to_uuid6($hex) {
998
        $hex = uuid_canonize($hex);
999
        if ($hex === false) return false;
1000
        $hex = preg_replace('@[^0-9A-F]@i', '', $hex);
1001
        $hex = substr($hex, 13, 3).
1002
               substr($hex, 8, 4).
1003
               substr($hex, 0, 5).
1004
               '6' . substr($hex, 5, 3).
1005
               substr($hex, 16);
1006
        return substr($hex,  0, 8).'-'.
1007
               substr($hex,  8, 4).'-'.
1008
               substr($hex, 12, 4).'-'.
1009
               substr($hex, 16, 4).'-'.
1010
               substr($hex, 20, 12);
1011
}
1012
 
1013
# --------------------------------------
1014
// Variant 1, Version 7 (Unix Epoch) UUID
1015
# --------------------------------------
1016
 
1017
function gen_uuid_v7() {
1018
        return gen_uuid_unix_epoch();
1019
}
1020
function gen_uuid_unix_epoch() {
1021
        // Start with an UUIDv4
1022
        $uuid = gen_uuid_random();
1023
 
1024
        // Add the timestamp
1025
        usleep(1); // make sure the timestamp is not repeated
1026
        if (function_exists('gmp_init')) {
1027
                list($ms,$sec) = explode(' ', microtime(false));
1028
                $sec = gmp_init($sec, 10);
1029
                $ms = gmp_init(substr($ms,2,3), 10);
1030
                $unix_ts = gmp_strval(gmp_add(gmp_mul($sec, '1000'), $ms),16);
1031
        } else {
1032
                $unix_ts = dechex((int)round(microtime(true)*1000));
1033
        }
1034
        $unix_ts = str_pad($unix_ts, 12, '0', STR_PAD_LEFT);
1035
        for ($i=0;$i<8;$i++) $uuid[$i] = substr($unix_ts, $i, 1);
1036
        for ($i=0;$i<4;$i++) $uuid[9+$i] = substr($unix_ts, 8+$i, 1);
1037
 
1038
        // set version
1039
        $uuid[14] = '7';
1040
 
1041
        return $uuid;
1042
}
1043
 
1044
# --------------------------------------
34 daniel-mar 1045
// Variant 1, Version 8 (Custom) UUID
1046
# --------------------------------------
30 daniel-mar 1047
 
34 daniel-mar 1048
function gen_uuid_v8($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit) {
1049
        return gen_uuid_custom($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit);
1050
}
1051
function gen_uuid_custom($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit) {
1052
        if (preg_replace('@[0-9A-F]@i', '', $block1_32bit) != '') throw new Exception("Invalid data for block 1. Must be hex input");
1053
        if (preg_replace('@[0-9A-F]@i', '', $block2_16bit) != '') throw new Exception("Invalid data for block 2. Must be hex input");
1054
        if (preg_replace('@[0-9A-F]@i', '', $block3_12bit) != '') throw new Exception("Invalid data for block 3. Must be hex input");
1055
        if (preg_replace('@[0-9A-F]@i', '', $block4_14bit) != '') throw new Exception("Invalid data for block 4. Must be hex input");
1056
        if (preg_replace('@[0-9A-F]@i', '', $block5_48bit) != '') throw new Exception("Invalid data for block 5. Must be hex input");
1057
 
1058
        $block1 = str_pad(substr($block1_32bit, -8),  8, '0', STR_PAD_LEFT);
1059
        $block2 = str_pad(substr($block2_16bit, -4),  4, '0', STR_PAD_LEFT);
1060
        $block3 = str_pad(substr($block3_12bit, -4),  4, '0', STR_PAD_LEFT);
1061
        $block4 = str_pad(substr($block4_14bit, -4),  4, '0', STR_PAD_LEFT);
1062
        $block5 = str_pad(substr($block5_48bit,-12), 12, '0', STR_PAD_LEFT);
1063
 
1064
        $block3[0] = '8'; // Version 8 = Custom
1065
        $block4[0] = dechex((hexdec($block4[0])&3) + 0b1000); // Variant 0b10__ = RFC4122
1066
 
1067
        return strtolower($block1.'-'.$block2.'-'.$block3.'-'.$block4.'-'.$block5);
1068
}
1069
 
1070
# --------------------------------------
1071
 
2 daniel-mar 1072
// http://php.net/manual/de/function.hex2bin.php#113057
1073
if ( !function_exists( 'hex2bin' ) ) {
1074
    function hex2bin( $str ) {
1075
        $sbin = "";
1076
        $len = strlen( $str );
1077
        for ( $i = 0; $i < $len; $i += 2 ) {
1078
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
1079
        }
1080
 
1081
        return $sbin;
1082
    }
1083
}