diff --git a/includes/utilities.inc b/includes/utilities.inc index ec155eb9..eadf1960 100644 --- a/includes/utilities.inc +++ b/includes/utilities.inc @@ -764,3 +764,63 @@ function islandora_get_content_models($ignore_system_namespace = TRUE) { } return $content_models; } + +/** + * This method will return a valid UUID based on V4 methods. + * + * @return string + * A valid V4 UUID. + */ +function get_uuid() { + $bytes = openssl_random_pseudo_bytes(2); + $add_mask = convert_hex_to_bin('4000'); + $negate_mask = convert_hex_to_bin('C000'); + // Make start with 11. + $manipulated_bytes = $bytes | $negate_mask; + // Make start with 01. + $manipulated_bytes = $manipulated_bytes ^ $add_mask; + $hex_string_10 = bin2hex($manipulated_bytes); + + return sprintf('%08s-%04s-4%03s-%s-%012s', + bin2hex(openssl_random_pseudo_bytes(4)), + bin2hex(openssl_random_pseudo_bytes(2)), + // Four most significant bits holds version number 4. + substr(bin2hex(openssl_random_pseudo_bytes(2)), 1), + // Two most significant bits holds zero and one for variant DCE1.1 + $hex_string_10, + bin2hex(openssl_random_pseudo_bytes(6)) + ); +} + +/** + * Will convert a hexadecimal string into a representative byte string. + * + * @note + * This method can be eliminated in PHP >= 5.4. + * http://php.net/manual/en/function.hex2bin.php#110973 + * + * @param string $hex + * A string representation of a hexadecimal number. + * + * @return string + * A byte string holding the bits indicated by the hex string. + */ +function convert_hex_to_bin($hex) { + $length_of_hex = strlen($hex); + $byte_string = ""; + $byte_counter = 0; + while ($byte_counter < $length_of_hex) { + $current_hex_byte = substr($hex, $byte_counter, 2); + $current_binary_byte = pack("H*", $current_hex_byte); + + if ($byte_counter == 0) { + $byte_string = $current_binary_byte; + } + else { + $byte_string .= $current_binary_byte; + } + $byte_counter += 2; + } + + return $byte_string; +}