Skip to content

Commit

Permalink
Merge pull request #19 from chrode/add-captcha
Browse files Browse the repository at this point in the history
Add new Field type Captcha to use FriendlyCaptcha
  • Loading branch information
chrode authored Jul 10, 2024
2 parents 6f9372d + 060a625 commit 935a05c
Show file tree
Hide file tree
Showing 11 changed files with 195 additions and 4 deletions.
17 changes: 16 additions & 1 deletion Classes/Controller/EmailController.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ public function createAction(\Slub\SlubForms\Domain\Model\Email $newEmail, array

}

} else if ($field->getType() == 'Captcha') {

$content[$field->getTitle()] = '-';

} else {

$content[$field->getTitle()] = empty($getfields[$field->getUid()]) ? '-' : $getfields[$field->getUid()];
Expand Down Expand Up @@ -302,6 +306,11 @@ public function createAction(\Slub\SlubForms\Domain\Model\Email $newEmail, array
$newEmail->setSenderName('-');
}

// set sender IP when config is set
if ($this->settings['storeSenderIP']) {
$newEmail->setSenderIp(GeneralUtility::getIndpEnv('REMOTE_ADDR'));
}

$settings = array();
// add signal before sending Email
$this->signalSlotDispatcher->dispatch(
Expand Down Expand Up @@ -336,9 +345,15 @@ public function createAction(\Slub\SlubForms\Domain\Model\Email $newEmail, array
}

// email to form owner

$senderEmail = $newEmail->getSenderEmail();
if($this->settings['overwriteFromEmailAdressToOwner'] && strlen($this->settings['overwriteFromEmailAdressToOwner']) > 0) {
$senderEmail = $this->settings['overwriteFromEmailAdressToOwner'];
}

$this->sendTemplateEmail(
array($form->getRecipient() => ''),
array($newEmail->getSenderEmail() => $newEmail->getSenderName()),
array($senderEmail => $newEmail->getSenderName()),
LocalizationUtility::translate('tx_slubforms_domain_model_email.form', 'slub_forms') . ': ' . $form->getTitle() . ': '. $newEmail->getSenderName(). ', '. $newEmail->getSenderEmail() ,
'FormEmail',
array( 'email' => $newEmail,
Expand Down
26 changes: 26 additions & 0 deletions Classes/Domain/Model/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class Email extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
*/
protected $senderEmail;

/**
* senderIp
*
* @var string
*/
protected $senderIp;

/**
* content
*
Expand Down Expand Up @@ -165,4 +172,23 @@ public function setEditcode($editcode) {
$this->editcode = $editcode;
}

/**
* Returns the senderIp
*
* @return string $senderIp
*/
public function getSenderIp() {
return $this->senderIp;
}

/**
* Sets the senderIp
*
* @param string $senderIp
* @return void
*/
public function setSenderIp($senderIp) {
$this->senderIp = $senderIp;
}

}
24 changes: 23 additions & 1 deletion Classes/Domain/Validator/FieldValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public function isValid($field) {
}
}
break;
default:
default:
if ($singleField->getRequired()) {
if (empty($getfields[$singleField->getUid()])) {
$error = $this->objectManager->get(\TYPO3\CMS\Extbase\Error\Error::class, 'val_default', 2000);
Expand Down Expand Up @@ -290,6 +290,28 @@ public function isValid($field) {
}
}
}

if ($singleField->getType() == 'Captcha') {

$config = \Slub\SlubForms\Helper\ArrayHelper::configToArray($singleField->getConfiguration());
$captchaService = GeneralUtility::makeInstance(\Slub\SlubForms\Service\Captcha\FriendlyCaptcha::class);
$validCaptcha = $captchaService->verify($getfields[$singleField->getUid()], $config);

if ($singleField->getRequired()) {
if (!$validCaptcha) {
$error = $this->objectManager->get(\TYPO3\CMS\Extbase\Error\Error::class, 'val_captcha', 2100);
$this->result->forProperty('content')->addError($error);
$this->isValid = false;
}
}
if ($fieldset->getRequired()) {
if ($validCaptcha) {
$fieldGroupOk++;
}
}

}

}

// if fieldset is required, check fields once more...
Expand Down
50 changes: 50 additions & 0 deletions Classes/Service/Captcha/FriendlyCaptcha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php
namespace Slub\SlubForms\Service\Captcha;

use GuzzleHttp\Client;

class FriendlyCaptcha {

CONST API_URL = 'https://api.friendlycaptcha.com/api/v1/siteverify';

/**
* This class represents the FriendlyCaptcha service for verifing CAPTCHA challenges.
*
* @param string $solution
* @param array $config
* @return bool
*/
public function verify(string $solution, $config = []) {

if (!$solution) {
return false;
}

$options = [
'headers' => ['Cache-Control' => 'no-cache'],
'allow_redirects' => true,
'form_params' => [
'secret' => $config['secret'],
'sitekey' => $config['sitekey'],
'solution' => $solution,
],
];

$client = new Client();
$contents = $client->request('POST', self::API_URL, $options);

if (!$contents) {
return false;
}

try {
$result = json_decode($contents->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR);

} catch (\JsonException $e) {
return false;
}

return (bool)$result->success;
}

}
42 changes: 42 additions & 0 deletions Classes/ViewHelpers/Form/ParseConfigurationViewHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php
namespace Slub\SlubForms\ViewHelpers\Form;

use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

class ParseConfigurationViewHelper extends AbstractViewHelper {


/**
* Register arguments.
* @return void
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('configurationString', 'string', 'Config string', true);

}

/**
* @return string
*/
public static function renderStatic(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext
) {

$templateVariableContainer = $renderingContext->getVariableProvider();

if ($templateVariableContainer->exists('configuration')) {
$templateVariableContainer->remove('configuration');
}
$templateVariableContainer->add('configuration', \Slub\SlubForms\Helper\ArrayHelper::configToArray($arguments['configurationString']));

return $renderChildrenClosure();

}


}
9 changes: 9 additions & 0 deletions Configuration/TCA/tx_slubforms_domain_model_email.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,15 @@
'eval' => 'trim'
],
],
'sender_ip' => [
'exclude' => 0,
'label' => 'LLL:EXT:slub_forms/Resources/Private/Language/locallang_db.xlf:tx_slubforms_domain_model_email.sender_ip',
'config' => [
'type' => 'input',
'size' => 255,
'eval' => 'trim'
],
],
'content' => [
'exclude' => 0,
'label' => 'LLL:EXT:slub_forms/Resources/Private/Language/locallang_db.xlf:tx_slubforms_domain_model_email.content',
Expand Down
2 changes: 2 additions & 0 deletions Configuration/TCA/tx_slubforms_domain_model_fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
['Submit', 'Submit'],
['-- special fields --', '--div--'],
['Description', 'Description'],
['Captcha', 'Captcha'],
],
'size' => 1,
'maxitems' => 1,
Expand Down Expand Up @@ -268,6 +269,7 @@
['Url', 'url'],
['Checkbox', 'checkbox'],
['Radiobutton', 'radiobutton'],
['Captcha', 'captcha'],
],
'size' => 1,
'maxitems' => 1,
Expand Down
6 changes: 5 additions & 1 deletion Configuration/TypoScript/setup.typoscript
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ plugin.tx_slubforms {
skipDefaultArguments = 1
}
settings {
senderEmailAddress = [email protected]
senderEmailAddress = [email protected]

overwriteFromEmailAdressToOwner = [email protected]

// allow sending anonymous mails
#anonymEmails {
Expand All @@ -21,6 +23,8 @@ plugin.tx_slubforms {

// send email to customer as confirmation
sendConfirmationEmailToCustomer = 1

storeSenderIP = 0
}
}

Expand Down
18 changes: 18 additions & 0 deletions Resources/Private/Partials/Forms/Captcha.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{namespace sf=Slub\SlubForms\ViewHelpers}
<script
type="module"
src="https://cdn.jsdelivr.net/npm/[email protected]/widget.module.min.js"
async
defer
></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/[email protected]/widget.min.js" async defer></script>


<div class="field_description">
<f:form.hidden name="field[{fieldset.uid}][{field.uid}]" class="{field.shortname}" />
<f:format.raw><sf:form.parseConfiguration configurationString="{field.configuration}">
<div class="frc-captcha" data-sitekey="{configuration.sitekey}" data-lang="de" data-start="auto" data-solution-field-name="tx_slubforms_sf[field][{fieldset.uid}][{field.uid}]"></div>
</sf:form.parseConfiguration></f:format.raw>

<label class="error" for="tx_slubforms_sf[field][{fieldset.uid}][{field.uid}]"></label>
</div>
4 changes: 3 additions & 1 deletion Resources/Private/Templates/Email/Create.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ <h3 class="formtitle"><f:link.page>

<ul>
<f:for each="{content}" key="fieldname" as="line">
<li><b>{fieldname}</b>: <f:format.nl2br>{line}</f:format.nl2br></li>
<f:if condition="{fieldname} != 'Captcha'">
<li><b>{fieldname}</b>: <f:format.nl2br>{line}</f:format.nl2br></li>
</f:if>
</f:for>
</ul>

Expand Down
1 change: 1 addition & 0 deletions ext_tables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ CREATE TABLE tx_slubforms_domain_model_email (

sender_name varchar(255) DEFAULT '' NOT NULL,
sender_email varchar(255) DEFAULT '' NOT NULL,
sender_ip varchar(255) DEFAULT '' NOT NULL,
content text NOT NULL,
editcode varchar(255) DEFAULT '' NOT NULL,
form int(11) unsigned DEFAULT '0',
Expand Down

0 comments on commit 935a05c

Please sign in to comment.