Subversion Repositories uuid_mac_utils

Rev

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