diff --git a/booking.earlyaccess_admin.inc b/booking.earlyaccess_admin.inc index dc7a373..e853eb1 100644 --- a/booking.earlyaccess_admin.inc +++ b/booking.earlyaccess_admin.inc @@ -103,25 +103,6 @@ function booking_earlyaccess_generate_codes() { return t("Created $num_codes_to_add early access codes."); } -/** - * Function to calculate unique code - * @see https://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string - * Requires PHP7 - */ -function booking_getToken($length) { - $token = ""; - $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - //$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz"; - $codeAlphabet.= "0123456789"; - $max = strlen($codeAlphabet); // edited - - for ($i=0; $i < $length; $i++) { - $token .= $codeAlphabet[random_int(0, $max-1)]; - } - - return $token; -} - /** * Function to generate csv of early access codes for the current event */ @@ -181,4 +162,71 @@ function booking_earlyaccess_csv_report() { drupal_add_http_header("Content-Disposition", "attachment; filename=" . $name . ".csv"); print $csv; exit(0); -} \ No newline at end of file +} + +/** + * Function to calculate unique code + * @see https://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string + * Requires PHP7 + */ + function booking_getToken($length) { + $token = ""; + $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + //$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz"; + $codeAlphabet.= "0123456789"; + $max = strlen($codeAlphabet); // edited + + if (!function_exists('random_int')) { + function random_int($min, $max) { + if (!function_exists('mcrypt_create_iv')) { + trigger_error( + 'mcrypt must be loaded for random_int to work', + E_USER_WARNING + ); + return null; + } + + if (!is_int($min) || !is_int($max)) { + trigger_error('$min and $max must be integer values', E_USER_NOTICE); + $min = (int)$min; + $max = (int)$max; + } + + if ($min > $max) { + trigger_error('$max can\'t be lesser than $min', E_USER_WARNING); + return null; + } + + $range = $counter = $max - $min; + $bits = 1; + + while ($counter >>= 1) { + ++$bits; + } + + $bytes = (int)max(ceil($bits/8), 1); + $bitmask = pow(2, $bits) - 1; + + if ($bitmask >= PHP_INT_MAX) { + $bitmask = PHP_INT_MAX; + } + + do { + $result = hexdec( + bin2hex( + mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM) + ) + ) & $bitmask; + } while ($result > $range); + + return $result + $min; + } + } + + for ($i=0; $i < $length; $i++) { + $token .= $codeAlphabet[random_int(0, $max-1)]; + } + + return $token; +} +