From 5041ffdb0f67660b4295021b0db094479665bdff Mon Sep 17 00:00:00 2001
From: Ruben Estrada <rulotec1@gmail.com>
Date: Mon, 26 Jul 2021 18:01:05 -0500
Subject: [PATCH] #954 updates recaptcha

---
 include/recaptcha/recaptchalib.php            | 277 ------------------
 .../v7/modules/Settings/Webforms/ShowForm.tpl |   6 +-
 .../Webforms/modules/Webforms/capture.php     |  66 ++++-
 .../modules/Webforms/config.captcha.php       |   5 +-
 .../settings/actions/CheckCaptcha.php         |  66 -----
 .../Webforms/settings/views/ShowForm.php      |   6 +-
 6 files changed, 63 insertions(+), 363 deletions(-)
 delete mode 100644 include/recaptcha/recaptchalib.php
 delete mode 100644 pkg/vtiger/modules/Webforms/settings/actions/CheckCaptcha.php

diff --git a/include/recaptcha/recaptchalib.php b/include/recaptcha/recaptchalib.php
deleted file mode 100644
index 32c4f4d75..000000000
--- a/include/recaptcha/recaptchalib.php
+++ /dev/null
@@ -1,277 +0,0 @@
-<?php
-/*
- * This is a PHP library that handles calling reCAPTCHA.
- *    - Documentation and latest version
- *          http://recaptcha.net/plugins/php/
- *    - Get a reCAPTCHA API Key
- *          https://www.google.com/recaptcha/admin/create
- *    - Discussion group
- *          http://groups.google.com/group/recaptcha
- *
- * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
- * AUTHORS:
- *   Mike Crawford
- *   Ben Maurer
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-/**
- * The reCAPTCHA server URL's
- */
-define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
-define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
-define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
-
-/**
- * Encodes the given data into a query string format
- * @param $data - array of string elements to be encoded
- * @return string - encoded request
- */
-function _recaptcha_qsencode ($data) {
-        $req = "";
-        foreach ( $data as $key => $value )
-                $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
-
-        // Cut the last '&'
-        $req=substr($req,0,strlen($req)-1);
-        return $req;
-}
-
-
-
-/**
- * Submits an HTTP POST to a reCAPTCHA server
- * @param string $host
- * @param string $path
- * @param array $data
- * @param int port
- * @return array response
- */
-function _recaptcha_http_post($host, $path, $data, $port = 80) {
-
-        $req = _recaptcha_qsencode ($data);
-
-        $http_request  = "POST $path HTTP/1.0\r\n";
-        $http_request .= "Host: $host\r\n";
-        $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
-        $http_request .= "Content-Length: " . strlen($req) . "\r\n";
-        $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
-        $http_request .= "\r\n";
-        $http_request .= $req;
-
-        $response = '';
-        if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
-                die ('Could not open socket');
-        }
-
-        fwrite($fs, $http_request);
-
-        while ( !feof($fs) )
-                $response .= fgets($fs, 1160); // One TCP-IP packet
-        fclose($fs);
-        $response = explode("\r\n\r\n", $response, 2);
-
-        return $response;
-}
-
-
-
-/**
- * Gets the challenge HTML (javascript and non-javascript version).
- * This is called from the browser, and the resulting reCAPTCHA HTML widget
- * is embedded within the HTML form it was called from.
- * @param string $pubkey A public key for reCAPTCHA
- * @param string $error The error given by reCAPTCHA (optional, default is null)
- * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
-
- * @return string - The HTML to be embedded in the user's form.
- */
-function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
-{
-	if ($pubkey == null || $pubkey == '') {
-		die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
-	}
-	
-	if ($use_ssl) {
-                $server = RECAPTCHA_API_SECURE_SERVER;
-        } else {
-                $server = RECAPTCHA_API_SERVER;
-        }
-
-        $errorpart = "";
-        if ($error) {
-           $errorpart = "&amp;error=" . $error;
-        }
-        return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
-
-	<noscript>
-  		<iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
-  		<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
-  		<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
-	</noscript>';
-}
-
-
-
-
-/**
- * A ReCaptchaResponse is returned from recaptcha_check_answer()
- */
-class ReCaptchaResponse {
-        var $is_valid;
-        var $error;
-}
-
-
-/**
-  * Calls an HTTP POST function to verify if the user's guess was correct
-  * @param string $privkey
-  * @param string $remoteip
-  * @param string $challenge
-  * @param string $response
-  * @param array $extra_params an array of extra variables to post to the server
-  * @return ReCaptchaResponse
-  */
-function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
-{
-	if ($privkey == null || $privkey == '') {
-		die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
-	}
-
-	if ($remoteip == null || $remoteip == '') {
-		die ("For security reasons, you must pass the remote ip to reCAPTCHA");
-	}
-
-	
-	
-        //discard spam submissions
-        if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
-                $recaptcha_response = new ReCaptchaResponse();
-                $recaptcha_response->is_valid = false;
-                $recaptcha_response->error = 'incorrect-captcha-sol';
-                return $recaptcha_response;
-        }
-
-        $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
-                                          array (
-                                                 'privatekey' => $privkey,
-                                                 'remoteip' => $remoteip,
-                                                 'challenge' => $challenge,
-                                                 'response' => $response
-                                                 ) + $extra_params
-                                          );
-
-        $answers = explode ("\n", $response [1]);
-        $recaptcha_response = new ReCaptchaResponse();
-
-        if (trim ($answers [0]) == 'true') {
-                $recaptcha_response->is_valid = true;
-        }
-        else {
-                $recaptcha_response->is_valid = false;
-                $recaptcha_response->error = $answers [1];
-        }
-        return $recaptcha_response;
-
-}
-
-/**
- * gets a URL where the user can sign up for reCAPTCHA. If your application
- * has a configuration page where you enter a key, you should provide a link
- * using this function.
- * @param string $domain The domain where the page is hosted
- * @param string $appname The name of your application
- */
-function recaptcha_get_signup_url ($domain = null, $appname = null) {
-	return "https://www.google.com/recaptcha/admin/create?" .  _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
-}
-
-function _recaptcha_aes_pad($val) {
-	$block_size = 16;
-	$numpad = $block_size - (strlen ($val) % $block_size);
-	return str_pad($val, strlen ($val) + $numpad, chr($numpad));
-}
-
-/* Mailhide related code */
-
-function _recaptcha_aes_encrypt($val,$ky) {
-	if (! function_exists ("mcrypt_encrypt")) {
-		die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
-	}
-	$mode=MCRYPT_MODE_CBC;   
-	$enc=MCRYPT_RIJNDAEL_128;
-	$val=_recaptcha_aes_pad($val);
-	return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
-}
-
-
-function _recaptcha_mailhide_urlbase64 ($x) {
-	return strtr(base64_encode ($x), '+/', '-_');
-}
-
-/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
-function recaptcha_mailhide_url($pubkey, $privkey, $email) {
-	if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
-		die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
-		     "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
-	}
-	
-
-	$ky = pack('H*', $privkey);
-	$cryptmail = _recaptcha_aes_encrypt ($email, $ky);
-	
-	return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
-}
-
-/**
- * gets the parts of the email to expose to the user.
- * eg, given johndoe@example,com return ["john", "example.com"].
- * the email is then displayed as john...@example.com
- */
-function _recaptcha_mailhide_email_parts ($email) {
-	$arr = preg_split("/@/", $email );
-
-	if (strlen ($arr[0]) <= 4) {
-		$arr[0] = substr ($arr[0], 0, 1);
-	} else if (strlen ($arr[0]) <= 6) {
-		$arr[0] = substr ($arr[0], 0, 3);
-	} else {
-		$arr[0] = substr ($arr[0], 0, 4);
-	}
-	return $arr;
-}
-
-/**
- * Gets html to display an email address given a public an private key.
- * to get a key, go to:
- *
- * http://www.google.com/recaptcha/mailhide/apikey
- */
-function recaptcha_mailhide_html($pubkey, $privkey, $email) {
-	$emailparts = _recaptcha_mailhide_email_parts ($email);
-	$url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
-	
-	return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
-		"' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]);
-
-}
-
-
-?>
diff --git a/pkg/vtiger/modules/Webforms/layouts/v7/modules/Settings/Webforms/ShowForm.tpl b/pkg/vtiger/modules/Webforms/layouts/v7/modules/Settings/Webforms/ShowForm.tpl
index ce8b18076..a07754253 100644
--- a/pkg/vtiger/modules/Webforms/layouts/v7/modules/Settings/Webforms/ShowForm.tpl
+++ b/pkg/vtiger/modules/Webforms/layouts/v7/modules/Settings/Webforms/ShowForm.tpl
@@ -118,15 +118,13 @@
 						{/foreach}
 					</table>
 					{if $IS_CAPTCHA_ENABLED}
-						<div id="captchaField"></div>
-						<input type="hidden" id="captchaUrl" value="{$CAPTCHA_PATH}">
-						<input type="hidden" id="recaptcha_validation_value" >
+						<script src="https://www.google.com/recaptcha/api.js" async defer></script>
+						<div class="g-recaptcha" data-sitekey="{$CAPTCHA_CONFIG['VTIGER_RECAPTCHA_PUBLIC_KEY']}" data-callback="enableSubmitBtn"></div>
 					{/if}
 					<input type="submit" value="Submit" ></input>
 				</form>
 				</pre>
 			</code>
-			<input type="hidden" name="isCaptchaEnabled" value="{$IS_CAPTCHA_ENABLED}">
 		</div>
 		<div class="modal-footer">
 			<center>
diff --git a/pkg/vtiger/modules/Webforms/modules/Webforms/capture.php b/pkg/vtiger/modules/Webforms/modules/Webforms/capture.php
index 1057ce381..6fef058db 100644
--- a/pkg/vtiger/modules/Webforms/modules/Webforms/capture.php
+++ b/pkg/vtiger/modules/Webforms/modules/Webforms/capture.php
@@ -10,17 +10,18 @@
 // Switch the working directory to base
 chdir(dirname(__FILE__) . '/../..');
 
-include_once 'includes/Loader.php';
-include_once 'include/Zend/Json.php';
-include_once 'vtlib/Vtiger/Module.php';
-include_once 'include/utils/VtlibUtils.php';
-include_once 'include/Webservices/Create.php';
-include_once 'modules/Webforms/model/WebformsModel.php';
-include_once 'modules/Webforms/model/WebformsFieldModel.php';
-include_once 'include/QueryGenerator/QueryGenerator.php';
-include_once 'includes/runtime/EntryPoint.php';
-include_once 'includes/main/WebUI.php';
-include_once 'include/Webservices/AddRelated.php';
+require_once 'includes/Loader.php';
+require_once 'include/Zend/Json.php';
+require_once 'vtlib/Vtiger/Module.php';
+require_once 'include/utils/VtlibUtils.php';
+require_once 'include/Webservices/Create.php';
+require_once 'modules/Webforms/model/WebformsModel.php';
+require_once 'modules/Webforms/model/WebformsFieldModel.php';
+require_once 'include/QueryGenerator/QueryGenerator.php';
+require_once 'includes/runtime/EntryPoint.php';
+require_once 'includes/main/WebUI.php';
+require_once 'include/Webservices/AddRelated.php';
+require_once 'modules/Webforms/config.captcha.php';
 
 class Webform_Capture {
 
@@ -36,9 +37,15 @@ class Webform_Capture {
 				throw new Exception('webforms is not active');
 
 			$webform = Webforms_Model::retrieveWithPublicId(vtlib_purify($request['publicid']));
-			if (empty($webform))
+			if (empty($webform)) {
 				throw new Exception("Webform not found.");
+			}
 
+			$webformSettingsRecord = Settings_Webforms_Record_Model::getInstanceById($webform->getId(), 'Settings:Webforms');
+			if ($webformSettingsRecord->isCaptchaEnabled()) {
+				$this->validateRecaptcha($request['g-recaptcha-response']);
+			}
+			
 			$returnURL = $webform->getReturnUrl();
 			$roundrobin = $webform->getRoundrobin();
 
@@ -156,6 +163,40 @@ class Webform_Capture {
 		}
 	}
 
+	private function validateRecaptcha($recaptchaResponse)
+	{
+		$recaptchaValidation = $this->postCaptcha($recaptchaResponse);
+		
+		if (!$recaptchaValidation['success']) {
+			throw new Exception("Please verify you are not a robot.");
+		}
+	}
+	
+	private function postCaptcha($recaptchaResponse) {
+		global $captchaConfig;
+		
+		$fields_string = '';
+		$fields = array(
+			'secret' => $captchaConfig['VTIGER_RECAPTCHA_PRIVATE_KEY'],
+			'response' => $recaptchaResponse
+		);
+		foreach($fields as $key=>$value) {
+			$fields_string .= $key . '=' . $value . '&';
+		}
+
+		$fields_string = rtrim($fields_string, '&');
+		
+		$ch = curl_init();
+		curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
+		curl_setopt($ch, CURLOPT_POST, count($fields));
+		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
+		
+		$result = curl_exec($ch);
+		curl_close($ch);
+		
+		return json_decode($result, true);
+	}
 }
 
 // NOTE: Take care of stripping slashes...
@@ -179,4 +220,3 @@ if ($isURLEncodeEnabled == 1) {
 } else {
 	$webformCapture->captureNow($request);
 }
-?>
\ No newline at end of file
diff --git a/pkg/vtiger/modules/Webforms/modules/Webforms/config.captcha.php b/pkg/vtiger/modules/Webforms/modules/Webforms/config.captcha.php
index 175d810fe..7118afc6f 100644
--- a/pkg/vtiger/modules/Webforms/modules/Webforms/config.captcha.php
+++ b/pkg/vtiger/modules/Webforms/modules/Webforms/config.captcha.php
@@ -13,7 +13,8 @@
  */
 global $captchaConfig;
 $captchaConfig=array(
-        'VTIGER_RECAPTCHA_PUBLIC_KEY'=>'RECAPTCHA PUBLIC KEY FOR THIS DOMAIN',//RECAPTCHA PUBLIC KEY FOR THIS DOMAIN
-'VTIGER_RECAPTCHA_PRIVATE_KEY'=>'RECAPTCHA PRIVATE KEY FOR THIS DOMAIN');//RECAPTCHA PRIVATE KEY FOR THIS DOMAIN
+    'VTIGER_RECAPTCHA_PUBLIC_KEY'=>'RECAPTCHA PUBLIC KEY FOR THIS DOMAIN',//RECAPTCHA PUBLIC KEY FOR THIS DOMAIN
+    'VTIGER_RECAPTCHA_PRIVATE_KEY'=>'RECAPTCHA PRIVATE KEY FOR THIS DOMAIN'//RECAPTCHA PRIVATE KEY FOR THIS DOMAIN
+);
 
 
diff --git a/pkg/vtiger/modules/Webforms/settings/actions/CheckCaptcha.php b/pkg/vtiger/modules/Webforms/settings/actions/CheckCaptcha.php
deleted file mode 100644
index 2d3bd9a4f..000000000
--- a/pkg/vtiger/modules/Webforms/settings/actions/CheckCaptcha.php
+++ /dev/null
@@ -1,66 +0,0 @@
-<?php
-/*+**********************************************************************************
- * The contents of this file are subject to the vtiger CRM Public License Version 1.1
- * ("License"); You may not use this file except in compliance with the License
- * The Original Code is: vtiger CRM Open Source
- * The Initial Developer of the Original Code is vtiger.
- * Portions created by vtiger are Copyright (C) vtiger.
- * All Rights Reserved.
- ************************************************************************************/
-
-// Switch the working directory to base
-chdir(dirname(__FILE__) . '/../../../..');
-
-include_once 'includes/http/Response.php';
-include_once 'vtlib/Vtiger/Module.php';
-include_once 'include/utils/VtlibUtils.php';
-include_once 'include/recaptcha/recaptchalib.php';
-
-class Webform_CheckCaptcha {
-
-	function checkCaptchaNow($request) {
-        // reCAPTCHA public and private keys to validate
-		$publickey = "6Lchg-wSAAAAAIkV51_LSksz6fFdD2vgy59jwa38";
-        $privatekey = "6Lchg-wSAAAAABUvZ57ogylowuv8SK0Hq4h2Yghs";
-
-        // to store the response from reCAPTCHA
-        $resp = null;
-
-        if ($request["recaptcha_response_field"]) {
-                $resp = recaptcha_check_answer ($privatekey,
-                                                $_SERVER["REMOTE_ADDR"],
-                                                $request["recaptcha_challenge_field"],
-                                                $request["recaptcha_response_field"]);
-
-                if ($resp->is_valid) {
-                        $this->sendResponse(true, $request['callId']);
-                } else {
-                        $this->sendResponse(false, $request['callId']);
-                }
-        } else {
-			$this->sendResponse(false, $request['callId']);
-		}
-	}
-
-	protected function sendResponse($success, $callId) {
-        $response = new Vtiger_Response();
-        if ($success)
-            $response->setResult(array('success' => true, 'callId' => $callId));
-        else
-            $response->setResult(array('success' => false, 'callId' => $callId));
-
-        // Support JSONP
-        if (!empty($_REQUEST['callback'])) {
-            $callback = vtlib_purify($_REQUEST['callback']);
-            $response->setEmitType('4');
-            $response->setEmitJSONP($callback);
-            $response->emit();
-        } else {
-            $response->emit();
-        }
-	}
-}
-
-$webformCheckCaptcha = new Webform_CheckCaptcha;
-$webformCheckCaptcha->checkCaptchaNow(vtlib_purify($_REQUEST));
-?>
\ No newline at end of file
diff --git a/pkg/vtiger/modules/Webforms/settings/views/ShowForm.php b/pkg/vtiger/modules/Webforms/settings/views/ShowForm.php
index 2f8ba7bba..3f4be0dbe 100644
--- a/pkg/vtiger/modules/Webforms/settings/views/ShowForm.php
+++ b/pkg/vtiger/modules/Webforms/settings/views/ShowForm.php
@@ -8,6 +8,8 @@
  * All Rights Reserved.
  *************************************************************************************/
 
+require_once 'modules/Webforms/config.captcha.php';
+
 Class Settings_Webforms_ShowForm_View extends Settings_Vtiger_IndexAjax_View {
 
 	public function checkPermission(Vtiger_Request $request) {
@@ -20,10 +22,11 @@ Class Settings_Webforms_ShowForm_View extends Settings_Vtiger_IndexAjax_View {
 		if(!$recordId || !$currentUserPrivilegesModel->hasModulePermission($moduleModel->getId())) {
 			throw new AppException(vtranslate('LBL_PERMISSION_DENIED'));
 		}
-        return true;
+		return true;
 	}
 
 	public function process(Vtiger_Request $request) {
+		global $captchaConfig;
 		$recordId = $request->get('record');
 		$qualifiedModuleName = $request->getModule(false);
 		$moduleName = $request->getModule();
@@ -44,6 +47,7 @@ Class Settings_Webforms_ShowForm_View extends Settings_Vtiger_IndexAjax_View {
 		$viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
 		$viewer->assign('DOCUMENT_FILE_FIELDS', $recordModel->getFileFields());
 		$viewer->assign('ALLOWED_ALL_FILES_SIZE', $recordModel->getModule()->allowedAllFilesSize());
+		$viewer->assign('CAPTCHA_CONFIG', $captchaConfig);
 
 		echo $viewer->view('ShowForm.tpl', $qualifiedModuleName);
 	}
-- 
GitLab