uuid.inc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * @file
  4. * Enables ctools generated modules to use UUIDs without the UUID module enabled.
  5. * Per the ctools.module, this file only gets included if UUID doesn't exist.
  6. */
  7. /**
  8. * Pattern for detecting a valid UUID.
  9. */
  10. if (!defined('UUID_PATTERN')) {
  11. define('UUID_PATTERN', '[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}');
  12. }
  13. /**
  14. * Generates a UUID using the Windows internal GUID generator.
  15. *
  16. * @see http://php.net/com_create_guid
  17. */
  18. function _ctools_uuid_generate_com() {
  19. // Remove {} wrapper and make lower case to keep result consistent.
  20. return drupal_strtolower(trim(com_create_guid(), '{}'));
  21. }
  22. /**
  23. * Generates an universally unique identifier using the PECL extension.
  24. */
  25. function _ctools_uuid_generate_pecl() {
  26. $uuid_type = UUID_TYPE_DEFAULT;
  27. return uuid_create($uuid_type);
  28. }
  29. /**
  30. * Generates a UUID v4 using PHP code.
  31. *
  32. * Based on code from @see http://php.net/uniqid#65879 , but corrected.
  33. */
  34. function _ctools_uuid_generate_php() {
  35. // The field names refer to RFC 4122 section 4.1.2.
  36. return sprintf('%04x%04x-%04x-4%03x-%04x-%04x%04x%04x',
  37. // 32 bits for "time_low".
  38. mt_rand(0, 65535), mt_rand(0, 65535),
  39. // 16 bits for "time_mid".
  40. mt_rand(0, 65535),
  41. // 12 bits after the 0100 of (version) 4 for "time_hi_and_version".
  42. mt_rand(0, 4095),
  43. bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '10', 0, 2)),
  44. // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
  45. // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
  46. // 8 bits for "clk_seq_low" 48 bits for "node".
  47. mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)
  48. );
  49. }
  50. // This is wrapped in an if block to avoid conflicts with PECL's uuid_is_valid().
  51. /**
  52. * Check that a string appears to be in the format of a UUID.
  53. *
  54. * @param $uuid
  55. * The string to test.
  56. *
  57. * @return
  58. * TRUE if the string is well formed.
  59. */
  60. if (!function_exists('uuid_is_valid')) {
  61. function uuid_is_valid($uuid) {
  62. return preg_match('/^' . UUID_PATTERN . '$/', $uuid);
  63. }
  64. }