<?php

if(!function_exists('hash_equals'))
{
	function hash_equals($known_string, $user_string)
	{
		if(!is_string($known_string) || !is_string($user_string)) return false;

		$known_length = strlen($known_string);
		if($known_length !== strlen($user_string)) return false;

		$result = 0;
		for($i = 0; $i < $known_length; $i++)
			$result |= ord($known_string[$i]) ^ ord($user_string[$i]);

		return $result === 0;
	}
}

if(!function_exists('sendy_preferences_token'))
{
	function sendy_preferences_token($app_id, $email, $expires_at=0)
	{
		$app_id = (int)$app_id;
		$email = strtolower(trim($email));
		if($app_id < 1 || !filter_var($email, FILTER_VALIDATE_EMAIL)) return '';
		if(!$expires_at) $expires_at = time() + (86400 * 365);

		$payload = encrypt_val(json_encode(array(
			'app' => $app_id,
			'email' => $email,
			'exp' => (int)$expires_at
		)));
		$signature = hash_hmac('sha256', $payload, API_KEY);
		return $payload.'.'.$signature;
	}

	function sendy_preferences_token_data($token)
	{
		if(!is_string($token) || strlen($token) > 4096 || strpos($token, '.') === false) return false;
		$parts = explode('.', $token, 2);
		if(count($parts) !== 2 || !preg_match('/^[a-f0-9]{64}$/', $parts[1])) return false;

		$expected = hash_hmac('sha256', $parts[0], API_KEY);
		if(!hash_equals($expected, $parts[1])) return false;
		$data = json_decode(decrypt_string($parts[0]), true);
		if(!is_array($data) || empty($data['app']) || empty($data['email']) || empty($data['exp'])) return false;
		if((int)$data['exp'] < time() || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) return false;

		return array(
			'app' => (int)$data['app'],
			'email' => strtolower(trim($data['email'])),
			'exp' => (int)$data['exp']
		);
	}

	function sendy_preferences_url($app_path, $app_id, $email)
	{
		$token = sendy_preferences_token($app_id, $email);
		return rtrim($app_path, '/').'/preferences?t='.rawurlencode($token);
	}

	function sendy_replace_preferences_tags($html, $plain, $app_path, $app_id, $email)
	{
		$url = sendy_preferences_url($app_path, $app_id, $email);
		$html = str_replace('<preferences', '<a href="'.$url.'" ', $html);
		$html = str_replace('</preferences>', '</a>', $html);
		$html = str_replace('[preferences]', $url, $html);
		$plain = str_replace('[preferences]', $url, $plain);
		return array($html, $plain);
	}
}

?>
