Removed useless path fields from entity exports.
[project/uuid.git] / uuid.inc
1 <?php
2
3 /**
4 * @file
5 * Handling of universally unique identifiers.
6 */
7
8 /**
9 * Generates an universally unique identifier.
10 *
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.
14 *
15 * @return
16 * An UUID, made up of 32 hex digits and 4 hyphens.
17 */
18 function uuid_generate() {
19 $callback = drupal_static(__FUNCTION__);
20
21 if (empty($callback)) {
22 if (function_exists('uuid_create') && !function_exists('uuid_make')) {
23 $callback = '_uuid_generate_pecl';
24 }
25 elseif (function_exists('com_create_guid')) {
26 $callback = '_uuid_generate_com';
27 }
28 else {
29 $callback = '_uuid_generate_php';
30 }
31 }
32 return $callback();
33 }
34
35 /**
36 * Generate all missing UUIDs.
37 */
38 function uuid_sync_all() {
39 module_invoke_all('uuid_sync');
40 }
41
42 /**
43 * Check that a string appears to be in the format of a UUID.
44 *
45 * @param $uuid
46 * The string to test.
47 *
48 * @return
49 * TRUE if the string is well formed.
50 */
51 function uuid_is_valid($uuid) {
52 return preg_match("/^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/", $uuid);
53 }
54
55 /**
56 * Generates a UUID using the Windows internal GUID generator.
57 *
58 * @see http://php.net/com_create_guid
59 */
60 function _uuid_generate_com() {
61 // Remove {} wrapper and make lower case to keep result consistent.
62 return drupal_strtolower(trim(com_create_guid(), '{}'));
63 }
64
65 /**
66 * Generates an universally unique identifier using the PECL extension.
67 */
68 function _uuid_generate_pecl() {
69 return uuid_create(UUID_TYPE_DEFAULT);
70 }
71
72 /**
73 * Generates a UUID v4 using PHP code.
74 *
75 * @see http://php.net/uniqid#65879
76 */
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".
83 mt_rand(0, 65535),
84 // 12 bits before the 0100 of (version) 4 for "time_hi_and_version".
85 mt_rand(0, 4095),
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)
91 );
92 }