Subversion Repositories uuid_mac_utils

Rev

Rev 35 | Rev 37 | 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';
36 daniel-mar 29
const UUID_NAMEBASED_NS_X500_DN = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; // "DER or text encoding" according to RFC4122bis
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);
36 daniel-mar 143
                        // List of families taken from: https://github.com/uuid6/uuid6-ietf-draft/issues/26#issuecomment-1062164457
144
                        if ($family_dec == 0) {
145
                                $family_name = 'socket_$unspec';
146
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
147
                        }
148
                        else if ($family_dec == 1) {
149
                                $family_name = 'socket_$unix';
150
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
151
                        }
152
                        else if ($family_dec == 2) {
153
                                $family_name = 'socket_$internet (TCP/IP)';
28 daniel-mar 154
                                // 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
155
                                // := [
156
                                //    time_high := 16#458487df,
157
                                //    time_low := 16#9fb2,
158
                                //    reserved := 16#000,
159
                                //    family := chr(16#02),
160
                                //    host := [chr(16#c0), chr(16#64), chr(16#02), chr(16#03),
161
                                //             chr(16#00), chr(16#00), chr(16#00)]
162
                                //    ]
163
                                // This means that the IP address is 32 bits hex, and 32 bits are unused
164
                                $nodeid_desc = hexdec(substr($nodeid_hex,0,2)).'.'.
165
                                               hexdec(substr($nodeid_hex,2,2)).'.'.
166
                                               hexdec(substr($nodeid_hex,4,2)).'.'.
167
                                               hexdec(substr($nodeid_hex,6,2));
168
                                $rest = substr($nodeid_hex,8,6);
169
                                if ($rest != '000000') $nodeid_desc .= " + unexpected rest 0x$rest";
36 daniel-mar 170
                        }
171
                        else if ($family_dec == 3) {
172
                                $family_name = 'socket_$implink';
173
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
174
                        }
175
                        else if ($family_dec == 4) {
176
                                $family_name = 'socket_$pup';
177
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
178
                        }
179
                        else if ($family_dec == 5) {
180
                                $family_name = 'socket_$chaos';
181
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
182
                        }
183
                        else if ($family_dec == 6) {
184
                                $family_name = 'socket_$ns';
185
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
186
                        }
187
                        else if ($family_dec == 7) {
188
                                $family_name = 'socket_$nbs';
189
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
190
                        }
191
                        else if ($family_dec == 8) {
192
                                $family_name = 'socket_$ecma';
193
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
194
                        }
195
                        else if ($family_dec == 9) {
196
                                $family_name = 'socket_$datakit';
197
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
198
                        }
199
                        else if ($family_dec == 10) {
200
                                $family_name = 'socket_$ccitt';
201
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
202
                        }
203
                        else if ($family_dec == 11) {
204
                                $family_name = 'socket_$sna';
205
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
206
                        }
207
                        else if ($family_dec == 12) {
208
                                $family_name = 'socket_$unspec2';
209
                                $nodeid_desc = ''; // TODO: how to interprete the Node-ID of that family?
210
                        }
211
                        else if ($family_dec == 13) {
212
                                $family_name = 'socket_$dds (Data Link)';
28 daniel-mar 213
                                // 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
214
                                // = { 0x34dc23af,
215
                                //    0xf000,
216
                                //    0x0000,
217
                                //    0x0d,
218
                                //    {0x00, 0x00, 0x7c, 0x5f, 0x00, 0x00, 0x00} };
219
                                // https://github.com/cjsv/uuid/blob/master/Doc writes:
220
                                //    "Family 13 (dds) looks like node is 00 | nnnnnn 000000."
221
 
222
                                $nodeid_desc = '';
223
 
224
                                $start = substr($nodeid_hex,0,2);
225
                                if ($start != '00') $nodeid_desc .= "unexpected start 0x$start + ";
226
 
227
                                $nodeid_desc .= ($nodeid_dec >> 24) & 0xFFFFFF;
228
 
229
                                $rest = substr($nodeid_hex,8,6);
230
                                if ($rest != '000000') $nodeid_desc .= " + unexpected rest 0x$rest";
2 daniel-mar 231
                        } else {
29 daniel-mar 232
                                $family_name = "Unknown (Family $family_dec)"; # There are probably no more families
233
                                $nodeid_desc = "Unknown";
2 daniel-mar 234
                        }
29 daniel-mar 235
                        echo sprintf("%-32s %s\n", "Family:", "[0x$family_hex] $family_name");
2 daniel-mar 236
 
28 daniel-mar 237
                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$nodeid_hex] $nodeid_desc");
2 daniel-mar 238
 
239
                        break;
240
                case 1:
35 daniel-mar 241
                        // 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
242
 
30 daniel-mar 243
                        $version = hexdec(substr($uuid, 12, 1));
2 daniel-mar 244
 
30 daniel-mar 245
                        if ($version <= 2) {
246
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 (Leach-Mealling-Salz) / DCE 1.1");
247
                        } else if (($version >= 3) && ($version <= 5)) {
248
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 (Leach-Mealling-Salz)");
249
                        } else if (($version >= 6) && ($version <= 8)) {
250
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122bis (Leach-Mealling-Peabody-Davis)");
251
                        } else {
252
                                echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 ?");
253
                        }
254
 
2 daniel-mar 255
                        switch ($version) {
29 daniel-mar 256
                                case 6:
257
                                        /*
258
                                        Variant 1, Version 6 UUID
259
                                        - 48 bit High Time
260
                                        -  4 bit Version (fix 0x6)
261
                                        - 12 bit Low Time
262
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 263
                                        -  6 bit Clock Sequence High
264
                                        -  8 bit Clock Sequence Low
29 daniel-mar 265
                                        - 48 bit MAC Address
266
                                        */
31 daniel-mar 267
                                        echo sprintf("%-32s %s\n", "Version:", "[6] Reordered Time");
29 daniel-mar 268
                                        $uuid = substr($uuid,  0, 8).'-'.
269
                                                substr($uuid,  8, 4).'-'.
270
                                                substr($uuid, 12, 4).'-'.
271
                                                substr($uuid, 16, 4).'-'.
272
                                                substr($uuid, 20, 12);
273
                                        $uuid = uuid6_to_uuid1($uuid);
274
                                        $uuid = str_replace('-', '', $uuid);
275
 
276
                                /* fallthrough */
2 daniel-mar 277
                                case 1:
27 daniel-mar 278
                                        /*
279
                                        Variant 1, Version 1 UUID
280
                                        - 32 bit Low Time
281
                                        - 16 bit Mid Time
282
                                        -  4 bit Version (fix 0x1)
283
                                        - 12 bit High Time
28 daniel-mar 284
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 285
                                        -  6 bit Clock Sequence High
286
                                        -  8 bit Clock Sequence Low
27 daniel-mar 287
                                        - 48 bit MAC Address
288
                                        */
289
 
31 daniel-mar 290
                                        if ($version == 1) echo sprintf("%-32s %s\n", "Version:", "[1] Time-based with unique host identifier");
2 daniel-mar 291
 
292
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
293
                                        # 1/0,0000001 = 10000000
294
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).substr($uuid, 0, 8);
295
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 296
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
297
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
298
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
299
                                        $ts = gmp_strval($ts, 10);
300
                                        $ms = gmp_strval($ms, 10);
301
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7/*0.1us*/, '0', STR_PAD_LEFT).' GMT';
25 daniel-mar 302
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
2 daniel-mar 303
 
304
                                        $x = hexdec(substr($uuid, 16, 4));
305
                                        $dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
306
                                        $hex = substr($uuid, 16, 4);
25 daniel-mar 307
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 308
 
309
                                        $x = substr($uuid, 20, 12);
310
                                        $nodeid = '';
311
                                        for ($i=0; $i<6; $i++) {
312
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 313
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 314
                                        }
30 daniel-mar 315
                                        $nodeid = strtoupper($nodeid);
27 daniel-mar 316
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 317
 
318
                                        if (function_exists('decode_mac')) {
25 daniel-mar 319
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
29 daniel-mar 320
                                                decode_mac(strtoupper($nodeid));
2 daniel-mar 321
                                        }
322
 
323
                                        break;
324
                                case 2:
27 daniel-mar 325
                                        /*
326
                                        Variant 1, Version 2 UUID
327
                                        - 32 bit Local Domain Number
328
                                        - 16 bit Mid Time
329
                                        -  4 bit Version (fix 0x2)
330
                                        - 12 bit High Time
28 daniel-mar 331
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 332
                                        -  6 bit Clock Sequence
28 daniel-mar 333
                                        -  8 bit Local Domain
27 daniel-mar 334
                                        - 48 bit MAC Address
335
                                        */
336
 
28 daniel-mar 337
                                        // see also https://unicorn-utterances.com/posts/what-happened-to-uuid-v2
338
 
25 daniel-mar 339
                                        echo sprintf("%-32s %s\n", "Version:", "[2] DCE Security version");
2 daniel-mar 340
 
27 daniel-mar 341
                                        # 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".
342
                                        $x = substr($uuid, 18, 2);
343
                                        if ($x == '00') $domain_info = 'Person (POSIX: User-ID)';
344
                                        else if ($x == '01') $domain_info = 'Group (POSIX: Group-ID)';
345
                                        else if ($x == '02') $domain_info = 'Organization';
346
                                        else $domain_info = 'site-defined (Domain '.hexdec($x).')';
347
                                        echo sprintf("%-32s %s\n", "Local Domain:", "[0x$x] $domain_info");
348
 
2 daniel-mar 349
                                        # 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.
350
                                        $x = substr($uuid, 0, 8);
29 daniel-mar 351
                                        $dec = hexdec($x);
352
                                        echo sprintf("%-32s %s\n", "Local Domain Number:", "[0x$x] $dec");
2 daniel-mar 353
 
354
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
355
                                        # 1/0,0000001 = 10000000
356
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'00000000';
357
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 358
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
359
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
360
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
361
                                        $ts = gmp_strval($ts, 10);
362
                                        $ms = gmp_strval($ms, 10);
363
                                        $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 364
 
365
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'FFFFFFFF';
366
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 367
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000", 10));
368
                                        $ms = gmp_mod($ts, gmp_init("10000000", 10));
369
                                        $ts = gmp_div($ts, gmp_init("10000000", 10));
370
                                        $ts = gmp_strval($ts, 10);
371
                                        $ms = gmp_strval($ms, 10);
372
                                        $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 373
 
29 daniel-mar 374
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4)/*.'xxxxxxxx'*/;
25 daniel-mar 375
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts_min - $ts_max");
2 daniel-mar 376
 
28 daniel-mar 377
                                        $x = hexdec(substr($uuid, 16, 2));
378
                                        $dec = $x & 0x3F; // The highest 2 bits are used by "variant" (10xx)
379
                                        $hex = substr($uuid, 16, 2);
27 daniel-mar 380
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 381
 
382
                                        $x = substr($uuid, 20, 12);
383
                                        $nodeid = '';
384
                                        for ($i=0; $i<6; $i++) {
385
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 386
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 387
                                        }
30 daniel-mar 388
                                        $nodeid = strtoupper($nodeid);
27 daniel-mar 389
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 390
 
391
                                        if (function_exists('decode_mac')) {
25 daniel-mar 392
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
29 daniel-mar 393
                                                decode_mac(strtoupper($nodeid));
2 daniel-mar 394
                                        }
395
 
396
                                        break;
397
                                case 3:
28 daniel-mar 398
                                        /*
399
                                        Variant 1, Version 3 UUID
400
                                        - 48 bit Hash High
29 daniel-mar 401
                                        -  4 bit Version (fix 0x3)
28 daniel-mar 402
                                        - 12 bit Hash Mid
403
                                        -  2 bit Variant (fix 0b10)
404
                                        - 62 bit Hash Low
405
                                        */
406
 
25 daniel-mar 407
                                        echo sprintf("%-32s %s\n", "Version:", "[3] Name-based (MD5 hash)");
2 daniel-mar 408
 
409
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 410
 
2 daniel-mar 411
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 412
 
32 daniel-mar 413
                                        $var16a = strtoupper(dechex((hexdec($hash[16])&3) + 0x0/*00__*/));
414
                                        $var16b = strtoupper(dechex((hexdec($hash[16])&3) + 0x4/*01__*/));
415
                                        $var16c = strtoupper(dechex((hexdec($hash[16])&3) + 0x8/*10__*/));
416
                                        $var16d = strtoupper(dechex((hexdec($hash[16])&3) + 0xC/*11__*/));
2 daniel-mar 417
                                        $hash[16] = '?'; // was partially overwritten by variant
418
 
27 daniel-mar 419
                                        echo sprintf("%-32s %s\n", "MD5(Namespace+Subject):", "[0x$hash]");
420
                                        echo sprintf("%-32s %s\n", "", "                   ^");
421
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 422
 
423
                                        break;
424
                                case 4:
28 daniel-mar 425
                                        /*
426
                                        Variant 1, Version 4 UUID
427
                                        - 48 bit Random High
29 daniel-mar 428
                                        -  4 bit Version (fix 0x4)
28 daniel-mar 429
                                        - 12 bit Random Mid
430
                                        -  2 bit Variant (fix 0b10)
431
                                        - 62 bit Random Low
432
                                        */
433
 
25 daniel-mar 434
                                        echo sprintf("%-32s %s\n", "Version:", "[4] Random");
2 daniel-mar 435
 
25 daniel-mar 436
                                        $rand_line1 = '';
437
                                        $rand_line2 = '';
2 daniel-mar 438
                                        for ($i=0; $i<16; $i++) {
439
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
440
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
441
 
442
                                                if ($i == 6) {
25 daniel-mar 443
                                                        // was overwritten by version
444
                                                        $bin[0] = '?';
445
                                                        $bin[1] = '?';
446
                                                        $bin[2] = '?';
447
                                                        $bin[3] = '?';
2 daniel-mar 448
                                                } else if ($i == 8) {
25 daniel-mar 449
                                                        // was partially overwritten by variant
450
                                                        $bin[0] = '?';
451
                                                        $bin[1] = '?';
2 daniel-mar 452
                                                }
453
 
25 daniel-mar 454
                                                if ($i<8) $rand_line1 .= "$bin ";
455
                                                if ($i>=8) $rand_line2 .= "$bin ";
2 daniel-mar 456
                                        }
25 daniel-mar 457
                                        echo sprintf("%-32s %s\n", "Random bits:", trim($rand_line1));
458
                                        echo sprintf("%-32s %s\n", "",             trim($rand_line2));
2 daniel-mar 459
 
27 daniel-mar 460
                                        $rand_bytes = str_replace('-', '', strtolower($uuid));
461
                                        $rand_bytes[12] = '?'; // was overwritten by version
32 daniel-mar 462
                                        $var16a = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x0/*00__*/));
463
                                        $var16b = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x4/*01__*/));
464
                                        $var16c = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0x8/*10__*/));
465
                                        $var16d = strtoupper(dechex((hexdec($rand_bytes[16])&3) + 0xC/*11__*/));
27 daniel-mar 466
                                        $rand_bytes[16] = '?'; // was partially overwritten by variant
467
                                        echo sprintf("%-32s %s\n", "Random bytes:", "[0x$rand_bytes]");
468
                                        echo sprintf("%-32s %s\n", "", "                   ^");
469
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
470
 
2 daniel-mar 471
                                        break;
472
                                case 5:
28 daniel-mar 473
                                        /*
474
                                        Variant 1, Version 5 UUID
475
                                        - 48 bit Hash High
29 daniel-mar 476
                                        -  4 bit Version (fix 0x5)
28 daniel-mar 477
                                        - 12 bit Hash Mid
478
                                        -  2 bit Variant (fix 0b10)
479
                                        - 62 bit Hash Low
480
                                        */
481
 
25 daniel-mar 482
                                        echo sprintf("%-32s %s\n", "Version:", "[5] Name-based (SHA-1 hash)");
2 daniel-mar 483
 
484
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 485
 
2 daniel-mar 486
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 487
 
32 daniel-mar 488
                                        $var16a = strtoupper(dechex((hexdec($hash[16])&3) + 0x0/*00__*/));
489
                                        $var16b = strtoupper(dechex((hexdec($hash[16])&3) + 0x4/*01__*/));
490
                                        $var16c = strtoupper(dechex((hexdec($hash[16])&3) + 0x8/*10__*/));
491
                                        $var16d = strtoupper(dechex((hexdec($hash[16])&3) + 0xC/*11__*/));
2 daniel-mar 492
                                        $hash[16] = '?'; // was partially overwritten by variant
27 daniel-mar 493
 
2 daniel-mar 494
                                        $hash .= '????????'; // was cut off
495
 
27 daniel-mar 496
                                        echo sprintf("%-32s %s\n", "SHA1(Namespace+Subject):", "[0x$hash]");
497
                                        echo sprintf("%-32s %s\n", "", "                   ^");
498
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 499
 
500
                                        break;
27 daniel-mar 501
                                case 7:
29 daniel-mar 502
                                        /*
503
                                        Variant 1, Version 7 UUID
504
                                        - 48 bit Unix Time in milliseconds
505
                                        -  4 bit Version (fix 0x7)
506
                                        - 12 bit Random
507
                                        -  2 bit Variant (fix 0b10)
508
                                        - 62 bit Random
509
                                        */
510
 
31 daniel-mar 511
                                        echo sprintf("%-32s %s\n", "Version:", "[7] Unix Epoch Time");
29 daniel-mar 512
 
513
                                        $timestamp = substr($uuid, 0, 12);
30 daniel-mar 514
 
515
                                        // Timestamp: Split into seconds and milliseconds
29 daniel-mar 516
                                        $ts = gmp_init($timestamp, 16);
30 daniel-mar 517
                                        $ms = gmp_mod($ts, gmp_init("1000", 10));
518
                                        $ts = gmp_div($ts, gmp_init("1000", 10));
519
                                        $ts = gmp_strval($ts, 10);
520
                                        $ms = gmp_strval($ms, 10);
521
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 3/*ms*/, '0', STR_PAD_LEFT).' GMT';
29 daniel-mar 522
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
523
 
524
                                        $rand = '';
525
                                        for ($i=6; $i<16; $i++) {
526
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
527
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
528
 
529
                                                if ($i == 6) {
530
                                                        // was overwritten by version
531
                                                        $bin[0] = '?';
532
                                                        $bin[1] = '?';
533
                                                        $bin[2] = '?';
534
                                                        $bin[3] = '?';
535
                                                } else if ($i == 8) {
536
                                                        // was partially overwritten by variant
537
                                                        $bin[0] = '?';
538
                                                        $bin[1] = '?';
539
                                                }
540
 
541
                                                $rand .= "$bin ";
542
                                        }
543
                                        echo sprintf("%-32s %s\n", "Random bits:", trim($rand));
544
 
545
                                        $rand_bytes = substr(str_replace('-', '', strtolower($uuid)),13);
32 daniel-mar 546
                                        $var16a = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x0/*00__*/));
547
                                        $var16b = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x4/*01__*/));
548
                                        $var16c = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0x8/*10__*/));
549
                                        $var16d = strtoupper(dechex((hexdec($rand_bytes[3])&3) + 0xC/*11__*/));
29 daniel-mar 550
                                        $rand_bytes[3] = '?'; // was partially overwritten by variant
551
                                        echo sprintf("%-32s %s\n", "Random bytes:", "[0x$rand_bytes]");
552
                                        echo sprintf("%-32s %s\n", "", "      ^");
553
                                        echo sprintf("%-32s %s\n", "", "      $var16a, $var16b, $var16c, or $var16d");
554
 
555
                                        // TODO: convert to and from Base32 CROCKFORD ULID (make 2 methods in uuid_utils.inc.php)
556
                                        // e.g. ULID: 01GCZ05N3JFRKBRWKNGCQZGP44
557
                                        // "Be aware that all version 7 UUIDs may be converted to ULIDs but not all ULIDs may be converted to UUIDs."
558
 
27 daniel-mar 559
                                        break;
560
                                case 8:
29 daniel-mar 561
                                        /*
562
                                        Variant 1, Version 8 UUID
35 daniel-mar 563
                                        - 48 bit Custom data
29 daniel-mar 564
                                        -  4 bit Version (fix 0x8)
35 daniel-mar 565
                                        - 12 bit Custom data
29 daniel-mar 566
                                        -  2 bit Variant (fix 0b10)
35 daniel-mar 567
                                        - 62 bit Custom data
29 daniel-mar 568
                                        */
569
 
31 daniel-mar 570
                                        echo sprintf("%-32s %s\n", "Version:", "[8] Custom implementation");
29 daniel-mar 571
 
572
                                        $custom_data = substr($uuid,0,12).substr($uuid,13); // exclude version nibble
573
                                        $custom_data[15] = dechex(hexdec($custom_data[15])&3); // nibble was partially overwritten by variant
574
                                        $custom_data = strtolower($custom_data);
575
 
34 daniel-mar 576
                                        $custom_block1 = substr($uuid,  0, 8);
577
                                        $custom_block2 = substr($uuid,  8, 4);
578
                                        $custom_block3 = substr($uuid, 12, 4);
579
                                        $custom_block4 = substr($uuid, 16, 4);
580
                                        $custom_block5 = substr($uuid, 20);
581
 
582
                                        $custom_block3 = substr($custom_block3, 1); // remove version
583
                                        $custom_block4[0] = dechex(hexdec($custom_block4[0])&3); // remove variant
584
 
29 daniel-mar 585
                                        echo sprintf("%-32s %s\n", "Custom data:", "[0x$custom_data]");
34 daniel-mar 586
                                        echo sprintf("%-32s %s\n", "Custom block1 (32 bit):", "[0x$custom_block1]");
587
                                        echo sprintf("%-32s %s\n", "Custom block2 (16 bit):", "[0x$custom_block2]");
588
                                        echo sprintf("%-32s %s\n", "Custom block3 (12 bit):", "[0x$custom_block3]");
589
                                        echo sprintf("%-32s %s\n", "Custom block4 (14 bit):", "[0x$custom_block4]");
590
                                        echo sprintf("%-32s %s\n", "Custom block5 (48 bit):", "[0x$custom_block5]");
29 daniel-mar 591
 
27 daniel-mar 592
                                        break;
2 daniel-mar 593
                                default:
25 daniel-mar 594
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Unknown");
2 daniel-mar 595
                                        break;
596
                        }
597
 
598
                        break;
599
                case 2:
35 daniel-mar 600
                        // 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
601
 
31 daniel-mar 602
                        // TODO: Is there any scheme in that legacy Microsoft GUIDs?
27 daniel-mar 603
                        echo sprintf("%-32s %s\n", "Variant:", "[0b110] Reserved for Microsoft Corporation");
2 daniel-mar 604
                        break;
605
                case 3:
27 daniel-mar 606
                        echo sprintf("%-32s %s\n", "Variant:", "[0b111] Reserved for future use");
2 daniel-mar 607
                        break;
608
        }
28 daniel-mar 609
 
610
        if (!$echo) {
611
                $out = ob_get_contents();
612
                ob_end_clean();
613
                return $out;
31 daniel-mar 614
        } else {
615
                return true;
28 daniel-mar 616
        }
2 daniel-mar 617
}
618
 
619
function uuid_canonize($uuid) {
620
        if (!uuid_valid($uuid)) return false;
621
        return oid_to_uuid(uuid_to_oid($uuid));
622
}
623
 
624
function oid_to_uuid($oid) {
625
        if (!is_uuid_oid($oid)) return false;
626
 
8 daniel-mar 627
        if (substr($oid,0,1) == '.') {
2 daniel-mar 628
                $oid = substr($oid, 1);
629
        }
630
        $ary = explode('.', $oid);
631
 
632
        if (!isset($ary[2])) return false;
633
 
634
        $val = $ary[2];
635
 
636
        $x = gmp_init($val, 10);
637
        $y = gmp_strval($x, 16);
638
        $y = str_pad($y, 32, "0", STR_PAD_LEFT);
639
        return substr($y,  0, 8).'-'.
640
               substr($y,  8, 4).'-'.
641
               substr($y, 12, 4).'-'.
642
               substr($y, 16, 4).'-'.
643
               substr($y, 20, 12);
644
}
645
 
646
function is_uuid_oid($oid, $only_allow_root=false) {
9 daniel-mar 647
        if (substr($oid,0,1) == '.') $oid = substr($oid, 1); // remove leading dot
2 daniel-mar 648
 
649
        $ary = explode('.', $oid);
650
 
651
        if ($only_allow_root) {
652
                if (count($ary) != 3) return false;
653
        } else {
654
                if (count($ary) < 3) return false;
655
        }
656
 
657
        if ($ary[0] != '2') return false;
658
        if ($ary[1] != '25') return false;
659
        for ($i=2; $i<count($ary); $i++) {
660
                $v = $ary[$i];
661
                if (!is_numeric($v)) return false;
662
                if ($i == 2) {
663
                        // Must be in the range of 128 bit UUID
664
                        $test = gmp_init($v, 10);
665
                        if (strlen(gmp_strval($test, 16)) > 32) return false;
666
                }
667
                if ($v < 0) return false;
668
        }
669
 
670
        return true;
671
}
672
 
673
function uuid_to_oid($uuid) {
674
        if (!uuid_valid($uuid)) return false;
675
 
676
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
677
        $x = gmp_init($uuid, 16);
29 daniel-mar 678
        return '2.25.'.gmp_strval($x, 10);
2 daniel-mar 679
}
680
 
31 daniel-mar 681
function uuid_numeric_value($uuid) {
682
        $oid = uuid_to_oid($uuid);
683
        if (!$oid) return false;
684
        return substr($oid, strlen('2.25.'));
685
}
686
 
687
function uuid_c_syntax($uuid) {
688
        $uuid = str_replace('{', '', $uuid);
689
        return '{ 0x' . substr($uuid, 0, 8) .
690
                ', 0x' . substr($uuid, 9, 4) .
691
                ', 0x' . substr($uuid, 14, 4) .
692
                ', { 0x' . substr($uuid, 19, 2).
693
                ', 0x' . substr($uuid, 21, 2) .
694
                ', 0x' . substr($uuid, 24, 2) .
695
                ', 0x' . substr($uuid, 26, 2) .
696
                ', 0x' . substr($uuid, 28, 2) .
697
                ', 0x' . substr($uuid, 30, 2) .
698
                ', 0x' . substr($uuid, 32, 2) .
699
                ', 0x' . substr($uuid, 34, 2) . ' } }';
700
}
701
 
30 daniel-mar 702
function gen_uuid($prefer_mac_address_based = true) {
703
        $uuid = $prefer_mac_address_based ? gen_uuid_reordered()/*UUIDv6*/ : false;
704
        if ($uuid === false) $uuid = gen_uuid_unix_epoch()/*UUIDv7*/;
2 daniel-mar 705
        return $uuid;
706
}
707
 
30 daniel-mar 708
# --------------------------------------
709
// Variant 1, Version 1 (Time based) UUID
710
# --------------------------------------
28 daniel-mar 711
 
30 daniel-mar 712
function gen_uuid_v1() {
713
        return gen_uuid_timebased();
714
}
2 daniel-mar 715
function gen_uuid_timebased() {
716
        # On Debian: apt-get install php-uuid
717
        # extension_loaded('uuid')
718
        if (function_exists('uuid_create')) {
719
                # OSSP uuid extension like seen in php5-uuid at Debian 8
720
                /*
721
                $x = uuid_create($context);
722
                uuid_make($context, UUID_MAKE_V1);
723
                uuid_export($context, UUID_FMT_STR, $uuid);
724
                return trim($uuid);
725
                */
726
 
727
                # PECL uuid extension like seen in php-uuid at Debian 9
728
                return trim(uuid_create(UUID_TYPE_TIME));
729
        }
730
 
731
        # On Debian: apt-get install uuid-runtime
732
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
733
                $out = array();
734
                $ec = -1;
735
                exec('uuidgen -t 2>/dev/null', $out, $ec);
736
                if ($ec == 0) return trim($out[0]);
737
        }
738
 
739
        # If we hadn't any success yet, then implement the time based generation routine ourselves!
740
        # Based on https://github.com/fredriklindberg/class.uuid.php/blob/master/class.uuid.php
741
 
742
        $uuid = array(
743
                'time_low' => 0,                /* 32-bit */
744
                'time_mid' => 0,                /* 16-bit */
745
                'time_hi' => 0,                 /* 16-bit */
746
                'clock_seq_hi' => 0,            /*  8-bit */
747
                'clock_seq_low' => 0,           /*  8-bit */
748
                'node' => array()               /* 48-bit */
749
        );
750
 
751
        /*
752
         * Get current time in 100 ns intervals. The magic value
753
         * is the offset between UNIX epoch and the UUID UTC
754
         * time base October 15, 1582.
755
         */
29 daniel-mar 756
        usleep(1); // make sure the timestamp is not used before
2 daniel-mar 757
        $tp = gettimeofday();
758
        $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) + 0x01B21DD213814000;
759
 
760
        $uuid['time_low'] = $time & 0xffffffff;
761
        /* Work around PHP 32-bit bit-operation limits */
762
        $high = intval($time / 0xffffffff);
763
        $uuid['time_mid'] = $high & 0xffff;
764
        $uuid['time_hi'] = (($high >> 16) & 0xfff) | (1/*TimeBased*/ << 12);
765
 
766
        /*
767
         * We don't support saved state information and generate
768
         * a random clock sequence each time.
769
         */
24 daniel-mar 770
        $uuid['clock_seq_hi'] = 0x80 | _random_int(0, 64);
771
        $uuid['clock_seq_low'] = _random_int(0, 255);
2 daniel-mar 772
 
773
        /*
774
         * Node should be set to the 48-bit IEEE node identifier
775
         */
776
        $mac = get_mac_address();
777
        if ($mac) {
25 daniel-mar 778
                $node = str_replace('-','',str_replace(':','',$mac));
2 daniel-mar 779
                for ($i = 0; $i < 6; $i++) {
780
                        $uuid['node'][$i] = hexdec(substr($node, $i*2, 2));
781
                }
782
 
783
                /*
784
                 * Now output the UUID
785
                 */
786
                return sprintf(
787
                        '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
788
                        ($uuid['time_low']), ($uuid['time_mid']), ($uuid['time_hi']),
789
                        $uuid['clock_seq_hi'], $uuid['clock_seq_low'],
790
                        $uuid['node'][0], $uuid['node'][1], $uuid['node'][2],
791
                        $uuid['node'][3], $uuid['node'][4], $uuid['node'][5]);
792
        }
793
 
794
        # We cannot generate the timebased UUID!
795
        return false;
796
}
797
function get_mac_address() {
798
        static $detected_mac = false;
799
 
800
        if ($detected_mac !== false) { // false NOT null!
801
                return $detected_mac;
802
        }
803
 
804
        // TODO: This should actually be part of mac_utils.inc.php, but we need it
805
        //       here, and mac_utils.inc.php shall only be optional. What to do?
806
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
807
                // Windows
808
                $cmds = array(
809
                        "ipconfig /all", // faster
810
                        "getmac"
811
                );
812
                foreach ($cmds as $cmd) {
813
                        $out = array();
814
                        $ec = -1;
815
                        exec($cmd, $out, $ec);
816
                        if ($ec == 0) {
817
                                $out = implode("\n",$out);
818
                                $m = array();
31 daniel-mar 819
                                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 820
                                        $detected_mac = strtolower($m[1]);
2 daniel-mar 821
                                        return $detected_mac;
822
                                }
823
                        }
824
                }
825
        } else if (strtoupper(PHP_OS) == 'DARWIN') {
826
                // Mac OS X
827
                $cmds = array(
828
                        "networksetup -listallhardwareports 2>/dev/null",
829
                        "netstat -i 2>/dev/null"
830
                );
831
                foreach ($cmds as $cmd) {
832
                        $out = array();
833
                        $ec = -1;
834
                        exec($cmd, $out, $ec);
835
                        if ($ec == 0) {
836
                                $out = implode("\n",$out);
837
                                $m = array();
838
                                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)) {
839
                                        $detected_mac = $m[1];
840
                                        return $detected_mac;
841
                                }
842
                        }
843
                }
844
        } else {
845
                // Linux
8 daniel-mar 846
                $addresses = @glob('/sys/class/net/'.'*'.'/address');
847
                foreach ($addresses as $x) {
2 daniel-mar 848
                        if (!strstr($x,'/lo/')) {
849
                                $detected_mac = trim(file_get_contents($x));
850
                                return $detected_mac;
851
                        }
852
                }
853
                $cmds = array(
854
                        "netstat -ie 2>/dev/null",
855
                        "ifconfig 2>/dev/null" // only available for root (because it is in sbin)
856
                );
857
                foreach ($cmds as $cmd) {
858
                        $out = array();
859
                        $ec = -1;
860
                        exec($cmd, $out, $ec);
861
                        if ($ec == 0) {
862
                                $out = implode("\n",$out);
863
                                $m = array();
864
                                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)) {
865
                                        $detected_mac = $m[1];
866
                                        return $detected_mac;
867
                                }
868
                        }
869
                }
870
        }
871
 
872
        $detected_mac = null;
873
        return $detected_mac;
874
}
875
 
30 daniel-mar 876
# --------------------------------------
28 daniel-mar 877
// Variant 1, Version 2 (DCE Security) UUID
30 daniel-mar 878
# --------------------------------------
879
 
27 daniel-mar 880
define('DCE_DOMAIN_PERSON', 0);
881
define('DCE_DOMAIN_GROUP', 1);
882
define('DCE_DOMAIN_ORG', 2);
30 daniel-mar 883
function gen_uuid_v2($domain, $id) {
884
        return gen_uuid_dce($domain, $id);
885
}
2 daniel-mar 886
function gen_uuid_dce($domain, $id) {
31 daniel-mar 887
        if (($domain ?? '') === '') throw new Exception("Domain ID missing");
888
        if (!is_numeric($domain)) throw new Exception("Invalid Domain ID");
889
        if (($domain < 0) || ($domain > 255)) throw new Exception("Domain ID must be in range 0..255");
890
 
891
        if (($id ?? '') === '') throw new Exception("ID value missing");
892
        if (!is_numeric($id)) throw new Exception("Invalid ID value");
893
        if (($id < 0) || ($id > 4294967295)) throw new Exception("ID value must be in range 0..4294967295");
894
 
2 daniel-mar 895
        # Start with a version 1 UUID
896
        $uuid = gen_uuid_timebased();
897
 
27 daniel-mar 898
        # Add Domain Number
2 daniel-mar 899
        $uuid = str_pad(dechex($id), 8, '0', STR_PAD_LEFT) . substr($uuid, 8);
900
 
27 daniel-mar 901
        # Add Domain (this overwrites part of the clock sequence)
2 daniel-mar 902
        $uuid = substr($uuid,0,21) . str_pad(dechex($domain), 2, '0', STR_PAD_LEFT) . substr($uuid, 23);
903
 
904
        # Change version to 2
905
        $uuid[14] = '2';
906
 
907
        return $uuid;
908
}
909
 
30 daniel-mar 910
# --------------------------------------
28 daniel-mar 911
// Variant 1, Version 3 (MD5 name based) UUID
30 daniel-mar 912
# --------------------------------------
913
 
914
function gen_uuid_v3($namespace_uuid, $name) {
915
        return gen_uuid_md5_namebased($namespace_uuid, $name);
916
}
2 daniel-mar 917
function gen_uuid_md5_namebased($namespace_uuid, $name) {
31 daniel-mar 918
        if (($namespace_uuid ?? '') === '') throw new Exception("Namespace UUID missing");
919
        if (!uuid_valid($namespace_uuid)) throw new Exception("Invalid namespace UUID '$namespace_uuid'");
920
 
2 daniel-mar 921
        $namespace_uuid = uuid_canonize($namespace_uuid);
922
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
923
        $namespace_uuid = hex2bin($namespace_uuid);
924
 
925
        $hash = md5($namespace_uuid.$name);
926
        $hash[12] = '3'; // Set version: 3 = MD5
927
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
928
 
929
        return substr($hash,  0, 8).'-'.
930
               substr($hash,  8, 4).'-'.
931
               substr($hash, 12, 4).'-'.
932
               substr($hash, 16, 4).'-'.
933
               substr($hash, 20, 12);
934
}
935
 
30 daniel-mar 936
# --------------------------------------
28 daniel-mar 937
// Variant 1, Version 4 (Random) UUID
30 daniel-mar 938
# --------------------------------------
939
 
940
function gen_uuid_v4() {
941
        return gen_uuid_random();
942
}
2 daniel-mar 943
function gen_uuid_random() {
944
        # On Windows: Requires
945
        #    extension_dir = "C:\php-8.0.3-nts-Win32-vs16-x64\ext"
946
        #    extension=com_dotnet
31 daniel-mar 947
        // TODO: can we trust that com_create_guid() always outputs UUIDv4?
30 daniel-mar 948
        /*
2 daniel-mar 949
        if (function_exists('com_create_guid')) {
950
                return strtolower(trim(com_create_guid(), '{}'));
951
        }
30 daniel-mar 952
        */
2 daniel-mar 953
 
954
        # On Debian: apt-get install php-uuid
955
        # extension_loaded('uuid')
956
        if (function_exists('uuid_create')) {
957
                # OSSP uuid extension like seen in php5-uuid at Debian 8
958
                /*
959
                $x = uuid_create($context);
960
                uuid_make($context, UUID_MAKE_V4);
961
                uuid_export($context, UUID_FMT_STR, $uuid);
962
                return trim($uuid);
963
                */
964
 
965
                # PECL uuid extension like seen in php-uuid at Debian 9
966
                return trim(uuid_create(UUID_TYPE_RANDOM));
967
        }
968
 
969
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
970
                # On Debian: apt-get install uuid-runtime
971
                $out = array();
972
                $ec = -1;
973
                exec('uuidgen -r 2>/dev/null', $out, $ec);
974
                if ($ec == 0) return trim($out[0]);
975
 
976
                # On Debian Jessie: UUID V4 (Random)
977
                if (file_exists('/proc/sys/kernel/random/uuid')) {
978
                        return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
979
                }
980
        }
981
 
982
        # Make the UUID by ourselves
983
        # Source: http://rogerstringer.com/2013/11/15/generate-uuids-php
984
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
24 daniel-mar 985
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ),
986
                _random_int( 0, 0xffff ),
987
                _random_int( 0, 0x0fff ) | 0x4000,
988
                _random_int( 0, 0x3fff ) | 0x8000,
989
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ), _random_int( 0, 0xffff )
2 daniel-mar 990
        );
991
}
992
 
30 daniel-mar 993
# --------------------------------------
28 daniel-mar 994
// Variant 1, Version 5 (SHA1 name based) UUID
30 daniel-mar 995
# --------------------------------------
996
 
997
function gen_uuid_v5($namespace_uuid, $name) {
998
        return gen_uuid_sha1_namebased($namespace_uuid, $name);
999
}
2 daniel-mar 1000
function gen_uuid_sha1_namebased($namespace_uuid, $name) {
31 daniel-mar 1001
        if (($namespace_uuid ?? '') === '') throw new Exception("Namespace UUID missing");
1002
        if (!uuid_valid($namespace_uuid)) throw new Exception("Invalid namespace UUID '$namespace_uuid'");
1003
 
2 daniel-mar 1004
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
1005
        $namespace_uuid = hex2bin($namespace_uuid);
1006
 
1007
        $hash = sha1($namespace_uuid.$name);
1008
        $hash[12] = '5'; // Set version: 5 = SHA1
27 daniel-mar 1009
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "0b10__" (RFC4122/DCE1.1)
2 daniel-mar 1010
 
1011
        return substr($hash,  0, 8).'-'.
1012
               substr($hash,  8, 4).'-'.
1013
               substr($hash, 12, 4).'-'.
1014
               substr($hash, 16, 4).'-'.
1015
               substr($hash, 20, 12);
1016
}
1017
 
30 daniel-mar 1018
# --------------------------------------
1019
// Variant 1, Version 6 (Reordered) UUID
1020
# --------------------------------------
1021
 
1022
function gen_uuid_v6() {
1023
        return gen_uuid_reordered();
1024
}
1025
function gen_uuid_reordered() {
1026
        // Start with a UUIDv1
1027
        $uuid = gen_uuid_timebased();
1028
 
1029
        // Convert to UUIDv6
1030
        return uuid1_to_uuid6($uuid);
1031
}
1032
function uuid6_to_uuid1($hex) {
1033
        $hex = uuid_canonize($hex);
1034
        if ($hex === false) return false;
1035
        $hex = preg_replace('@[^0-9A-F]@i', '', $hex);
1036
        $hex = substr($hex, 7, 5).
1037
               substr($hex, 13, 3).
1038
               substr($hex, 3, 4).
1039
               '1' . substr($hex, 0, 3).
1040
               substr($hex, 16);
1041
        return substr($hex,  0, 8).'-'.
1042
               substr($hex,  8, 4).'-'.
1043
               substr($hex, 12, 4).'-'.
1044
               substr($hex, 16, 4).'-'.
1045
               substr($hex, 20, 12);
1046
}
1047
function uuid1_to_uuid6($hex) {
1048
        $hex = uuid_canonize($hex);
1049
        if ($hex === false) return false;
1050
        $hex = preg_replace('@[^0-9A-F]@i', '', $hex);
1051
        $hex = substr($hex, 13, 3).
1052
               substr($hex, 8, 4).
1053
               substr($hex, 0, 5).
1054
               '6' . substr($hex, 5, 3).
1055
               substr($hex, 16);
1056
        return substr($hex,  0, 8).'-'.
1057
               substr($hex,  8, 4).'-'.
1058
               substr($hex, 12, 4).'-'.
1059
               substr($hex, 16, 4).'-'.
1060
               substr($hex, 20, 12);
1061
}
1062
 
1063
# --------------------------------------
1064
// Variant 1, Version 7 (Unix Epoch) UUID
1065
# --------------------------------------
1066
 
1067
function gen_uuid_v7() {
1068
        return gen_uuid_unix_epoch();
1069
}
1070
function gen_uuid_unix_epoch() {
1071
        // Start with an UUIDv4
1072
        $uuid = gen_uuid_random();
1073
 
1074
        // Add the timestamp
1075
        usleep(1); // make sure the timestamp is not repeated
1076
        if (function_exists('gmp_init')) {
1077
                list($ms,$sec) = explode(' ', microtime(false));
1078
                $sec = gmp_init($sec, 10);
1079
                $ms = gmp_init(substr($ms,2,3), 10);
1080
                $unix_ts = gmp_strval(gmp_add(gmp_mul($sec, '1000'), $ms),16);
1081
        } else {
1082
                $unix_ts = dechex((int)round(microtime(true)*1000));
1083
        }
1084
        $unix_ts = str_pad($unix_ts, 12, '0', STR_PAD_LEFT);
1085
        for ($i=0;$i<8;$i++) $uuid[$i] = substr($unix_ts, $i, 1);
1086
        for ($i=0;$i<4;$i++) $uuid[9+$i] = substr($unix_ts, 8+$i, 1);
1087
 
1088
        // set version
1089
        $uuid[14] = '7';
1090
 
1091
        return $uuid;
1092
}
1093
 
1094
# --------------------------------------
34 daniel-mar 1095
// Variant 1, Version 8 (Custom) UUID
1096
# --------------------------------------
30 daniel-mar 1097
 
34 daniel-mar 1098
function gen_uuid_v8($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit) {
1099
        return gen_uuid_custom($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit);
1100
}
1101
function gen_uuid_custom($block1_32bit, $block2_16bit, $block3_12bit, $block4_14bit, $block5_48bit) {
1102
        if (preg_replace('@[0-9A-F]@i', '', $block1_32bit) != '') throw new Exception("Invalid data for block 1. Must be hex input");
1103
        if (preg_replace('@[0-9A-F]@i', '', $block2_16bit) != '') throw new Exception("Invalid data for block 2. Must be hex input");
1104
        if (preg_replace('@[0-9A-F]@i', '', $block3_12bit) != '') throw new Exception("Invalid data for block 3. Must be hex input");
1105
        if (preg_replace('@[0-9A-F]@i', '', $block4_14bit) != '') throw new Exception("Invalid data for block 4. Must be hex input");
1106
        if (preg_replace('@[0-9A-F]@i', '', $block5_48bit) != '') throw new Exception("Invalid data for block 5. Must be hex input");
1107
 
1108
        $block1 = str_pad(substr($block1_32bit, -8),  8, '0', STR_PAD_LEFT);
1109
        $block2 = str_pad(substr($block2_16bit, -4),  4, '0', STR_PAD_LEFT);
1110
        $block3 = str_pad(substr($block3_12bit, -4),  4, '0', STR_PAD_LEFT);
1111
        $block4 = str_pad(substr($block4_14bit, -4),  4, '0', STR_PAD_LEFT);
1112
        $block5 = str_pad(substr($block5_48bit,-12), 12, '0', STR_PAD_LEFT);
1113
 
1114
        $block3[0] = '8'; // Version 8 = Custom
1115
        $block4[0] = dechex((hexdec($block4[0])&3) + 0b1000); // Variant 0b10__ = RFC4122
1116
 
1117
        return strtolower($block1.'-'.$block2.'-'.$block3.'-'.$block4.'-'.$block5);
1118
}
1119
 
1120
# --------------------------------------
1121
 
2 daniel-mar 1122
// http://php.net/manual/de/function.hex2bin.php#113057
1123
if ( !function_exists( 'hex2bin' ) ) {
1124
    function hex2bin( $str ) {
1125
        $sbin = "";
1126
        $len = strlen( $str );
1127
        for ( $i = 0; $i < $len; $i += 2 ) {
1128
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
1129
        }
1130
 
1131
        return $sbin;
1132
    }
1133
}