indieauth/functions.php
2024-07-17 16:00:11 +01:00

81 lines
2 KiB
PHP

<?php
function create_signed_code(
$key,
$message,
$ttl = 31536000,
$appended_data = ""
) {
$expires = time() + $ttl;
$body = $message . $expires . $appended_data;
$signature = hash_hmac("sha256", $body, $key);
return dechex($expires) .
":" .
$signature .
":" .
base64_url_encode($appended_data);
}
function verify_signed_code($key, $message, $code) {
$code_parts = explode(":", $code, 3);
if (count($code_parts) !== 3) {
return false;
}
$expires = hexdec($code_parts[0]);
if (time() > $expires) {
return false;
}
$body = $message . $expires . base64_url_decode($code_parts[2]);
$signature = hash_hmac("sha256", $body, $key);
return hash_equals($signature, $code_parts[1]);
}
function filter_input_regexp($type, $variable, $regexp, $flags = null) {
$options = [
"options" => ["regexp" => $regexp],
];
if ($flags !== null) {
$options["flags"] = $flags;
}
return filter_input($type, $variable, FILTER_VALIDATE_REGEXP, $options);
}
function get_q_value($mime, $accept) {
$fulltype = preg_replace('@^([^/]+\/).+$@', '$1*', $mime);
$regex = implode("", [
"/(?<=^|,)\s*(\*\/\*|",
preg_quote($fulltype, "/"),
"|",
preg_quote($mime, "/"),
')\s*(?:[^,]*?;\s*q\s*=\s*([0-9.]+))?\s*(?:,|$)/',
]);
$out = preg_match_all($regex, $accept, $matches);
$types = array_combine($matches[1], $matches[2]);
if (array_key_exists($mime, $types)) {
$q = $types[$mime];
} elseif (array_key_exists($fulltype, $types)) {
$q = $types[$fulltype];
} elseif (array_key_exists("*/*", $types)) {
$q = $types["*/*"];
} else {
return 0;
}
return $q === "" ? 1 : floatval($q);
}
function base64_url_encode($string) {
$string = base64_encode($string);
$string = rtrim($string, "=");
$string = strtr($string, "+/", "-_");
return $string;
}
function base64_url_decode($string) {
$string = strtr($string, "-_", "+/");
$padding = strlen($string) % 4;
if ($padding !== 0) {
$string .= str_repeat("=", 4 - $padding);
}
$string = base64_decode($string);
return $string;
}