Subversion Repositories uuid_mac_utils

Rev

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