5 * Handling of universally unique identifiers.
9 * Generates an universally unique identifier.
11 * This function first checks for the PECL alternative for generating
12 * universally unique identifiers. If that doesn't exist, then it falls back on
13 * PHP for generating that.
16 * An UUID, made up of 32 hex digits and 4 hyphens.
18 function uuid_generate() {
19 $callback = drupal_static(__FUNCTION__
);
21 if (empty($callback)) {
22 if (function_exists('uuid_create') && !function_exists('uuid_make')) {
23 $callback = '_uuid_generate_pecl';
25 elseif (function_exists('com_create_guid')) {
26 $callback = '_uuid_generate_com';
29 $callback = '_uuid_generate_php';
36 * Generate all missing UUIDs.
38 function uuid_sync_all() {
39 module_invoke_all('uuid_sync');
43 * Check that a string appears to be in the format of a UUID.
49 * TRUE if the string is well formed.
51 function uuid_is_valid($uuid) {
52 return preg_match("/^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/", $uuid);
56 * Generates a UUID using the Windows internal GUID generator.
58 * @see http://php.net/com_create_guid
60 function _uuid_generate_com() {
61 // Remove {} wrapper and make lower case to keep result consistent.
62 return drupal_strtolower(trim(com_create_guid(), '{}'));
66 * Generates an universally unique identifier using the PECL extension.
68 function _uuid_generate_pecl() {
69 return uuid_create(UUID_TYPE_DEFAULT
);
73 * Generates a UUID v4 using PHP code.
75 * @see http://php.net/uniqid#65879
77 function _uuid_generate_php() {
78 // The field names refer to RFC 4122 section 4.1.2.
79 return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
80 // 32 bits for "time_low".
81 mt_rand(0, 65535), mt_rand(0, 65535),
82 // 16 bits for "time_mid".
84 // 12 bits before the 0100 of (version) 4 for "time_hi_and_version".
86 bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
87 // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
88 // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
89 // 8 bits for "clk_seq_low" 48 bits for "node".
90 mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)