add implementation of random_int for pre-PHP7

This commit is contained in:
2017-08-22 21:46:17 +10:00
parent 8e3b8e75c6
commit 12fdc944ab

View File

@@ -103,25 +103,6 @@ function booking_earlyaccess_generate_codes() {
return t("Created $num_codes_to_add early access 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 * Function to generate csv of early access codes for the current event
*/ */
@@ -182,3 +163,70 @@ function booking_earlyaccess_csv_report() {
print $csv; print $csv;
exit(0); exit(0);
} }
/**
* 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;
}