|
<?php |
|
|
|
/** |
|
* This is a library based on an original Google code that handles reCAPTCHA v3. |
|
* |
|
* @author Jakub KUBÍČEK <[email protected]> |
|
*/ |
|
|
|
|
|
/** |
|
* Represents a reCAPTCHA pool of successfuly completed challenges. |
|
*/ |
|
final class ReCaptcha |
|
{ |
|
private $secret; |
|
|
|
|
|
/** |
|
* @param string $secret shared secret between site and ReCAPTCHA server. |
|
*/ |
|
public function __construct($secret) |
|
{ |
|
$this->secret = $secret; |
|
} |
|
|
|
|
|
/** |
|
* Ask the pool if completed challenge token is valid. |
|
* |
|
* @param string user's response token for the reCAPTCHA challenge |
|
* @return bool |
|
*/ |
|
final public function valid($response) |
|
{ |
|
return !empty($response) |
|
&& json_decode($json = $this->apiResponse($response), TRUE)['success'] |
|
&& max(.4, json_decode($json, TRUE)['score']) !== .4; // above threshold |
|
} |
|
|
|
|
|
/** |
|
* @return string URL-encoded key-value pair |
|
*/ |
|
private function urlencoded($name, $value) |
|
{ |
|
return rawurlencode($name) . '=' . rawurlencode($value); |
|
} |
|
|
|
|
|
/** |
|
* @param array(string => string, ...) |
|
* @return string URL-encoded query string of key-value pairs |
|
*/ |
|
private function qsencoded(array $kvPairs) |
|
{ |
|
$pieces = []; |
|
foreach($kvPairs as $k => $v) { |
|
$pieces[] = $this->urlencoded($k, $v); |
|
} |
|
return implode('&', $pieces); |
|
} |
|
|
|
|
|
/** |
|
* Submits a HTTP GET to the reCAPTCHA server. |
|
* |
|
* @param array user's response token for the reCAPTCHA challenge |
|
* @return string JSON response |
|
*/ |
|
private function apiResponse($response) |
|
{ |
|
return file_get_contents( |
|
'https://www.google.com/recaptcha/api/siteverify', |
|
FALSE, |
|
stream_context_create([ |
|
'http' => [ |
|
'method' => 'POST', |
|
'content' => $this->qsencoded(['response' => $response, 'secret' => $this->secret]), |
|
'header' => 'Content-Type: application/x-www-form-urlencoded' |
|
] |
|
]) |
|
); |
|
} |
|
} |