Subversion Repositories oidplus

Rev

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

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