Home » Php » recaptcha – How to implement Google Recaptchav2 in Adobe Muse based PHP?

recaptcha – How to implement Google Recaptchav2 in Adobe Muse based PHP?

Posted by: admin February 25, 2020 Leave a comment

Questions:

does anyone here have any experience with dealing with PHP files that were created by Adobe Muse?

I’m still very very new to PHP and my father’s friend wanted me to create and implement a Google ReCaptcha to put on their contact page to avoid spam. I was able to get the recaptcha on the webpage itself and right now it “works” but not how it is supposed to, as yes, it will not let you send a form without doing the captcha, but there is no validation set in place or anywhere that has the secret key from recaptcha so my guess it is only validating if the captcha itself is done which I don’t think will reduce spam.

The HTML seems to call to a form-u36890.php with this code:

/*
If you see this text in your browser, PHP is not configured correctly on this hosting provider.
Contact your hosting provider regarding PHP configuration for your site.

PHP file generated by Adobe Muse CC 2018.1.0.386
*/

require_once('form_process.php');

$form = array(
    'subject' => 'Contact Form Submission',
    'heading' => 'New Form Submission',
    'success_redirect' => '',
    'resources' => array(
        'checkbox_checked' => 'Checked',
        'checkbox_unchecked' => 'Unchecked',
        'submitted_from' => 'Form submitted from website: %s',
        'submitted_by' => 'Visitor IP address: %s',
        'too_many_submissions' => 'Too many recent submissions from this IP',
        'failed_to_send_email' => 'Failed to send email',
        'invalid_reCAPTCHA_private_key' => 'Invalid reCAPTCHA private key.',
        'invalid_reCAPTCHA2_private_key' => 'Invalid reCAPTCHA 2.0 private key.',
        'invalid_reCAPTCHA2_server_response' => 'Invalid reCAPTCHA 2.0 server response.',
        'invalid_field_type' => 'Unknown field type \'%s\'.',
        'invalid_form_config' => 'Field \'%s\' has an invalid configuration.',
        'unknown_method' => 'Unknown server request method'
    ),
    'email' => array(
        'from' => 'email address here',
        'to' => 'email address here'
    ),
    'fields' => array(
        'custom_U36925' => array(
            'order' => 1,
            'type' => 'string',
            'label' => 'Name',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Name\' is required.'
            )
        ),
        'Email' => array(
            'order' => 2,
            'type' => 'email',
            'label' => 'Email',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Email\' is required.',
                'format' => 'Field \'Email\' has an invalid email.'
            )
        ),
        'custom_U36907' => array(
            'order' => 3,
            'type' => 'string',
            'label' => 'Company',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Company\' is required.'
            )
        ),
        'custom_U36899' => array(
            'order' => 4,
            'type' => 'string',
            'label' => 'Work Address',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Work Address\' is required.'
            )
        ),
        'custom_U36891' => array(
            'order' => 5,
            'type' => 'string',
            'label' => 'City',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'City\' is required.'
            )
        ),
        'custom_U36895' => array(
            'order' => 6,
            'type' => 'string',
            'label' => 'State',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'State\' is required.'
            )
        ),
        'custom_U36903' => array(
            'order' => 7,
            'type' => 'string',
            'label' => 'Zip code',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Zip code\' is required.'
            )
        ),
        'custom_U36921' => array(
            'order' => 8,
            'type' => 'string',
            'label' => 'Country',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Country\' is required.'
            )
        ),
        'custom_U36913' => array(
            'order' => 10,
            'type' => 'string',
            'label' => 'Message',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Message\' is required.'
            )
        ),
        'custom_U37014' => array(
            'order' => 9,
            'type' => 'string',
            'label' => 'Phone',
            'required' => true,
            'errors' => array(
                'required' => 'Field \'Phone\' is required.'
            )
        )
    )
);

process_form($form);
?>

I’ve tried editing stuff in here and also in form-process.php which has this code:

<?php 
/*  
If you see this text in your browser, PHP is not configured correctly on this hosting provider. 
Contact your hosting provider regarding PHP configuration for your site.
PHP file generated by Adobe Muse CC 2018.1.0.386
*/
require_once('form_throttle.php');
function process_form($form) {
if ($_SERVER['REQUEST_METHOD'] != 'POST')
die(get_form_error_response($form['resources']['unknown_method']));
if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
die(get_form_error_response($form['resources']['too_many_submissions']));
// will die() if there are any errors
check_required_fields($form);
// will die() if there is a send email problem
email_form_submission($form);
}
function get_form_error_response($error) {
return get_form_response(false, array('error' => $error));
}
function get_form_response($success, $data) {
if (!is_array($data))
die('data must be array');
$status = array();
$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
return json_serialize($status);
}
function check_required_fields($form) {
$errors = array();
foreach ($form['fields'] as $field => $properties) {
if (!$properties['required'])
continue;
if (!array_key_exists($field, $_REQUEST) || ($_REQUEST[$field] !== "0" && empty($_REQUEST[$field])))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
else if (!check_field_value_format($form, $field, $properties))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
}
if (!empty($errors))
die(get_form_error_response(array('fields' => $errors)));
}
function check_field_value_format($form, $field, $properties) {
$value = get_form_field_value($field, $properties, $form['resources'], false);
switch($properties['type']) {
case 'checkbox':
case 'string':
case 'captcha':
// no format to validate for those fields
return true;
case 'checkboxgroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
// If the value received is not an array, treat it as invalid format
if (!isset($value))
return false;
// Check each option to see if it is a valid value
foreach($value as $checkboxValue) {
if (!in_array($checkboxValue, $properties['optionItems']))
return false;
}
return true;
case 'radiogroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
//check list of real radio values
return in_array($value, $properties['optionItems']);
case 'recaptcha':
if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA_private_key']));
$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
return $resp->is_valid;
case 'recaptcha2':
if (!array_key_exists('recaptcha2', $form) || !array_key_exists('private_key', $form['recaptcha2']) || empty($form['recaptcha2']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA2_private_key']));
$resp = recaptcha2_check_answer($form['recaptcha2']['private_key'], $_POST["g-recaptcha-response"], $_SERVER["REMOTE_ADDR"]);
return $resp["success"];
case 'email':
return 1 == preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($form['resources']['invalid_field_type'], $properties['type'])));
}
}
/**
* Returns an object with following properties:
*  "success": true|false,
*  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
*  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
*  "error-codes": [...]        // optional; possibe values:
*                                  missing-input-secret - The secret parameter is missing
*                                  invalid-input-secret - The secret parameter is invalid or malformed
*                                  missing-input-response - The response parameter is missing
*                                  invalid-input-response - The response parameter is invalid or malformed
*/
function recaptcha2_check_answer($secret, $response, $remoteIP) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteIP
);
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
'method'  => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
if ($contents === FALSE) {
die(get_form_error_response($form['resources']['invalid_reCAPTCHA2_server_response']));
}
$result = (array) json_decode($contents);
return $result;
}
function email_form_submission($form) {
if(!defined('PHP_EOL'))
define('PHP_EOL', '\r\n');
$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');
$to = $form['email']['to'];
$subject = $form['subject'];
$message = get_email_body($subject, $form['heading'], $form['fields'], $form['resources']);
$headers = get_email_headers($to, $form_email); 
$sent = @mail($to, $subject, $message, $headers);
if(!$sent)
die(get_form_error_response($form['resources']['failed_to_send_email']));
$success_data = array(
'redirect' => $form['success_redirect']
);
echo get_form_response(true, $success_data);
}
function get_email_headers($to_email, $form_email) {
$headers = 'From: ' . $to_email . PHP_EOL;
$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
$headers .= 'X-Mailer: Adobe Muse CC 2018.1.0.386 with PHP' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
return $headers;
}
function get_email_body($subject, $heading, $fields, $resources) {
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">'; 
$sorted_fields = array();
foreach ($fields as $field => $properties) {
// Skip reCAPTCHA from email submission
if ('recaptcha' == $properties['type'] || 'recaptcha2' == $properties['type'])
continue;
array_push($sorted_fields, array('field' => $field, 'properties' => $properties));
}
// sort fields
usort($sorted_fields, 'field_comparer');
foreach ($sorted_fields as $field_wrapper)
$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($field_wrapper['properties']['label']) . ':</b></td><td>' . get_form_field_value($field_wrapper['field'], $field_wrapper['properties'], $resources, true) . '</td></tr>';
$message .= '</table>';
$message .= '<br/><br/>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_from'], encode_for_form($_SERVER['SERVER_NAME'])) . '</div>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_by'], encode_for_form($_SERVER['REMOTE_ADDR'])) . '</div>';
$message .= '</body></html>';
return cleanup_message($message);
}
function field_comparer($field1, $field2) {
if ($field1['properties']['order'] == $field2['properties']['order'])
return 0;
return (($field1['properties']['order'] < $field2['properties']['order']) ? -1 : 1);
}
function is_assoc_array($arr) {
if (!is_array($arr))
return false;
$keys = array_keys($arr);
foreach (array_keys($arr) as $key)
if (is_string($key)) return true;
return false;
}
function json_serialize($data) {
if (is_assoc_array($data)) {
$json = array();
foreach ($data as $key => $value)
array_push($json, '"' . $key . '": ' . json_serialize($value));
return '{' . implode(', ', $json) . '}';
}
if (is_array($data)) {
$json = array();
foreach ($data as $value)
array_push($json, json_serialize($value));
return '[' . implode(', ', $json) . ']';
}
if (is_int($data) || is_float($data))
return $data;
if (is_bool($data))
return $data ? 'true' : 'false';
return '"' . encode_for_json($data) . '"';
}
function encode_for_json($value) {
return preg_replace(array('/([\'"\\t\\\\])/i', '/\\r/i', '/\\n/i'), array('\\\\$1', '\\r', '\\n'), $value);
}
function encode_for_form($text) {
$text = stripslashes($text);
return htmlentities($text, ENT_QUOTES, 'UTF-8');// need ENT_QUOTES or webpro.js jQuery.parseJSON fails
}
function get_form_field_value($field, $properties, $resources, $forOutput) {
$value = $_REQUEST[$field];
switch($properties['type']) {
case 'checkbox':
return (($value == '1' || $value == 'true') ? $resources['checkbox_checked'] : $resources['checkbox_unchecked']);
case 'checkboxgroup':
if (!is_array($value))
return NULL;
$outputValue = array();
foreach ($value as $checkboxValue)
array_push($outputValue, $forOutput ? encode_for_form($checkboxValue) : stripslashes($checkboxValue));
if ($forOutput)
$outputValue = implode(', ', $outputValue);
return $outputValue;
case 'radiogroup':
return ($forOutput ? encode_for_form($value) : stripslashes($value));
case 'string':
case 'captcha':
case 'recaptcha':
case 'recaptcha2':
case 'email':
return encode_for_form($value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($resources['invalid_field_type'], $properties['type'])));
}
}
function cleanup_email($email) {
$email = encode_for_form($email);
$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $email);
return $email;
}
function cleanup_message($message) {
$message = wordwrap($message, 70, "\r\n");
return $message;
}
?>

but still no dice. I have a revised version of form-process.php that seems to work just fine inside of my localhost via xampp (I can post that revised version if needed. The ones above are the stock ones that are just from the website itself) I’ve tried uploading our fixed version that works on localhost and I get this error:

Form PHP script is missing from web server, or PHP is not configured correctly on your web hosting provider. Check if the form PHP script has been uploaded correctly, then contact your hosting provider about PHP configuration.

I’m legitimately lost at this point.

I’ve spent this whole weekend trying to implement it but keep getting stuck, as the php forms that come from Adobe Muse is rather confusing and messy and I’m unsure of where to even implement my php to verify the recaptcha. Most things that I also google showcase people adding recaptcha via inside of the Muse program itself which I don’t have access to, nor do I have the Muse files even I had the program.

Any help in this would be greatly appreciated, and I’m more than happy to share any more info if needed.

tl;dr: I need help implementing Google Recaptcha v2 onto a contact form, but all the php forms were created by Adobe Muse and I’m not sure where to actually drop in my code to make it work on the website.

How to&Answers: