1 | <?php |
||
2 | |||
3 | namespace Extend\Core\Captcha; |
||
4 | |||
5 | use Ffcms\Core\App; |
||
6 | use Ffcms\Core\Helper\FileSystem\File; |
||
7 | use Ffcms\Core\Interfaces\iCaptcha; |
||
8 | use Symfony\Component\HttpFoundation\Request; |
||
9 | |||
10 | class Recaptcha implements iCaptcha |
||
11 | { |
||
12 | private static $siteKey; |
||
13 | private static $secret; |
||
14 | |||
15 | /** |
||
16 | * Set site key (public key) and secret (private key) on init |
||
17 | * @param string $siteKey |
||
18 | * @param string $secret |
||
19 | */ |
||
20 | public function __construct($siteKey, $secret) |
||
21 | { |
||
22 | self::$siteKey = $siteKey; |
||
23 | self::$secret = $secret; |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * Check is captcha provide 'full-based' output realisation |
||
28 | * @return bool |
||
29 | */ |
||
30 | public function isFull() |
||
31 | { |
||
32 | return true; |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * Get captcha image link(isFull():=false) or builded JS code(isFull():=true) |
||
37 | * @return string |
||
38 | */ |
||
39 | public function get() |
||
40 | { |
||
41 | // build google captcha ;) |
||
42 | $html = '<div class="g-recaptcha" data-sitekey="' . self::$siteKey . '"></div> |
||
43 | <script type="text/javascript" |
||
44 | src="https://www.google.com/recaptcha/api.js?hl=' . App::$Request->getLanguage() . '"> |
||
45 | </script>'; |
||
46 | return $html; |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * Validate input data from captcha |
||
51 | * @param string|null $data |
||
52 | * @return bool |
||
53 | */ |
||
54 | public static function validate($data = null) |
||
55 | { |
||
56 | // nevertheless what we got in our model, recaptcha is suck and don't allow to change response field name |
||
57 | $data = App::$Request->get('g-recaptcha-response'); |
||
58 | |||
59 | // make validation |
||
60 | $request = Request::create('https://www.google.com/recaptcha/api/siteverify', 'GET', [ |
||
61 | 'secret' => self::$secret, |
||
62 | 'response' => $data, |
||
63 | 'remoteip' => App::$Request->getClientIp() |
||
64 | ]); |
||
65 | |||
66 | // make request and parse response |
||
67 | $url = $request->getSchemeAndHttpHost() . $request->getRequestUri(); |
||
68 | $response = File::getFromUrl($url); |
||
69 | $object = json_decode($response); |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
70 | |||
71 | return $object->success; |
||
72 | } |
||
73 | } |
||
74 |