<?php
/**
 * Verify a reCAPTCHA v2 response.
 * @param  string $token The token provided by Google.
 * @param  string $private_key The reCAPTCHA private key.
 * @return bool        True if the token is valid, false otherwise.
 */
function verify_recaptcha_v2($token, $private_key)
{
	$site = Mainframe::site();
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify?secret=" . $private_key . "&response=" . $token . "&remoteip=" . get_instance()->input->server("REMOTE_ADDR"));
	curl_setopt($curl, CURLOPT_POST, 0);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_HEADER, 0);  // DO NOT RETURN HTTP HEADERS
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  // RETURN THE CONTENTS OF THE CALL
	$data = json_decode(curl_exec($curl));
	curl_close($curl);

	return ($data->success == 1);
}

/**
 * Verify a reCAPTCHA v3 response.
 * @param  string $token  The token provided by Google.
 * @param  string $action The identifier for the action being tracked.
 * @return object         An object containing all of Google's response fields,
 *                        plus a boolean "passed" flag of our own and a status message of our own.
 *                        The "passed" flag is true if the user's score is equal to or
 *                        above our site's reCAPTCHA threshold value.
 */
function verify_recaptcha_v3($token, $action)
{
	$site = Mainframe::site();
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify?secret=" . $site->recaptcha_private_key . "&response=" . $token . "&remoteip=" . get_instance()->input->server("REMOTE_ADDR"));
	curl_setopt($curl, CURLOPT_POST, 0);
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_HEADER, 0);  // DO NOT RETURN HTTP HEADERS
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  // RETURN THE CONTENTS OF THE CALL
	$data = json_decode(curl_exec($curl));
	curl_close($curl);

	$data->passed = false;

	if(!$data->success)
	{
		$data->score = 0.0;
		$data->message = "Invalid Token";
	}
	else if($data->action != $action)
	{
		$data->score = 0.0;
		$data->message = "Action mismatch.";
	}
	else
	{
		if(!empty($_SERVER["SERVER_NAME"]) && $data->hostname != $_SERVER["SERVER_NAME"])
		{
			$data->score = 0.0;
			$data->message = "Hostname mismatch.";
		}
	}

	if($data->score >= $site->recaptcha_threshold)
	{
		$data->passed = true;
		$data->message = "Score is above configured threshold.";
	}
	else
	{
		$data->message = "Score is below configured threshold.";
	}

	return $data;
}