3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use CRM_Recaptcha_ExtensionUtil
as E
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Utils_ReCAPTCHA
{
21 protected $_captcha = NULL;
23 protected $_name = NULL;
25 protected $_url = NULL;
27 protected $_phrase = NULL;
32 * We only need one instance of this object. So we use the singleton
33 * pattern and cache the instance in this variable
35 * @var CRM_Utils_ReCAPTCHA
37 private static $_singleton = NULL;
40 * Singleton function used to manage this object.
44 public static function &singleton() {
45 if (self
::$_singleton === NULL) {
46 self
::$_singleton = new CRM_Utils_ReCAPTCHA();
48 return self
::$_singleton;
52 * Check if reCaptcha settings is avilable to add on form.
54 public static function hasSettingsAvailable() {
55 return (bool) \Civi
::settings()->get('recaptchaPublicKey');
59 * Add element to form.
61 * @param CRM_Core_Form $form
63 public static function add(&$form) {
66 // If we already added reCAPTCHA then don't add it again.
67 // The `recaptcha_get_html` function only exists once recaptchalib.php has been included via this function.
68 if (function_exists('recaptcha_get_html')) {
71 require_once E
::path('lib/recaptcha/recaptchalib.php');
73 // Load the Recaptcha api.js over HTTPS
76 $html = recaptcha_get_html(\Civi
::settings()->get('recaptchaPublicKey'), $error, $useHTTPS);
78 $form->assign('recaptchaHTML', $html);
79 $form->assign('recaptchaOptions', \Civi
::settings()->get('recaptchaOptions'));
82 'g-recaptcha-response',
87 $form->registerRule('recaptcha', 'callback', 'validate', 'CRM_Utils_ReCAPTCHA');
88 $form->addRule('g-recaptcha-response', E
::ts('Please go back and complete the CAPTCHA at the bottom of this form.'), 'recaptcha');
89 if ($form->isSubmitted() && empty($form->_submitValues
['g-recaptcha-response'])) {
90 $form->setElementError(
91 'g-recaptcha-response',
92 E
::ts('Please go back and complete the CAPTCHA at the bottom of this form.')
98 * Enable ReCAPTCHA on Contribution form
100 * @param CRM_Core_Form $form
102 public static function enableCaptchaOnForm(&$form) {
103 $captcha = CRM_Utils_ReCAPTCHA
::singleton();
104 if ($captcha->hasSettingsAvailable()) {
105 $captcha->add($form);
106 $form->assign('isCaptcha', TRUE);
112 * @param CRM_Core_Form $form
116 public static function validate($value, $form) {
117 $resp = recaptcha_check_answer(CRM_Core_Config
::singleton()->recaptchaPrivateKey
,
118 $_SERVER['REMOTE_ADDR'],
119 $_POST['g-recaptcha-response']
121 return $resp->is_valid
;