Merge pull request #718 from robertdown/procedure-providers
[openemr.git] / ccr / uuid.php
blob05f1d6a45e07a206ce4736542c28657946377c32
1 <?php
2 /*
3 * Generates a Universally Unique IDentifier, version 4.
5 * RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt) defines a special type of Globally
6 * Unique IDentifiers (GUID), as well as several methods for producing them. One
7 * such method, described in section 4.4, is based on truly random or pseudo-random
8 * number generators, and is therefore implementable in a language like PHP.
10 * We choose to produce pseudo-random numbers with the Mersenne Twister, and to always
11 * limit single generated numbers to 16 bits (ie. the decimal value 65535). That is
12 * because, even on 32-bit systems, PHP's RAND_MAX will often be the maximum *signed*
13 * value, with only the equivalent of 31 significant bits. Producing two 16-bit random
14 * numbers to make up a 32-bit one is less efficient, but guarantees that all 32 bits
15 * are random.
17 * The algorithm for version 4 UUIDs (ie. those based on random number generators)
18 * states that all 128 bits separated into the various fields (32 bits, 16 bits, 16 bits,
19 * 8 bits and 8 bits, 48 bits) should be random, except : (a) the version number should
20 * be the last 4 bits in the 3rd field, and (b) bits 6 and 7 of the 4th field should
21 * be 01. We try to conform to that definition as efficiently as possible, generating
22 * smaller values where possible, and minimizing the number of base conversions.
24 * @copyright Copyright (c) CFD Labs, 2006. This function may be used freely for
25 * any purpose ; it is distributed without any form of warranty whatsoever.
26 * @author David Holmes <dholmes@cfdsoftware.net>
28 * @return string A UUID, made up of 32 hex digits and 4 hyphens.
31 function getUuid() {
33 // The field names refer to RFC 4122 section 4.1.2
35 return sprintf('A%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
36 mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
37 mt_rand(0, 65535), // 16 bits for "time_mid"
38 mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
39 bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
40 // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
41 // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
42 // 8 bits for "clk_seq_low"
43 mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"