SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/Recaptcha.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use Exception;
  17.  
  18. use Kohana;
  19.  
  20.  
  21. /**
  22. * Implementation of Google (No CAPTCHA) ReCAPTCHA
  23. **/
  24. class Recaptcha
  25. {
  26.  
  27. /**
  28.   * Shows the captcha field
  29.   **/
  30. public static function field()
  31. {
  32. $key = Kohana::config('sprout.recaptcha_public_key');
  33. if (!$key) throw new Exception('ReCAPTCHA key not found');
  34.  
  35. Needs::addJavascriptInclude('https://www.google.com/recaptcha/api.js');
  36. echo '<div class="g-recaptcha" data-sitekey="' . Enc::html($key) . '"></div>';
  37. }
  38.  
  39. /**
  40.   * Checks the captcha field against the submitted text
  41.   * @return boolean True on success
  42.   **/
  43. public static function check()
  44. {
  45. if (empty($_POST['g-recaptcha-response'])) {
  46. // Obviously not a valid request if there's no captcha response.
  47.  
  48. return false;
  49. }
  50.  
  51. $key = Kohana::config('sprout.recaptcha_private_key');
  52. if (!$key) throw new Exception('ReCAPTCHA key not found');
  53.  
  54. // prep data for post
  55. $data = array();
  56. $data['secret'] = $key;
  57. $data['response'] = $_POST['g-recaptcha-response'];
  58. $data['remoteip'] = Request::userIp();
  59.  
  60. // post request and receive json answer
  61. $res = HttpReq::req('https://www.google.com/recaptcha/api/siteverify', array('method' => 'post'), $data);
  62. $res = json_decode($res, true);
  63.  
  64. // hopefully return true or false
  65. if (! is_bool($res['success'])) throw new Exception('Invalid captcha return data');
  66. return $res['success'];
  67. }
  68.  
  69. }
  70.  
  71.