<?php
namespace App\Controller;
use App\Service\NewsletterService;
use App\Twig\LayoutExtension;
use CustomerManagementFrameworkBundle\DataValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
use Elements\Bundle\HashCashBundle\Service\HashCashService;
use Pimcore\Mail;
use Pimcore\Model\DataObject\ContactTopic;
use Pimcore\Model\DataObject\CustomerSegment;
use Pimcore\Model\DataObject\Region;
use Pimcore\Model\Document;
use Pimcore\Model\Document\Email;
use Pimcore\Model\Document\Page;
use Pimcore\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
class FormController extends AbstractController
{
const COMPONENT = 'FormController';
private Translator $translator;
public function __construct(Translator $translator, protected LayoutExtension $layoutExtension)
{
$this->translator = $translator;
}
/**
* @param Request $request
* @param HashCashService $hashCashService
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Exception
*/
public function contactAction(Request $request, HashCashService $hashCashService)
{
$errors = [];
$success = null;
$mailValidator = new EmailValidator();
if ($request->isMethod('POST') && $request->get('potNumber') == '') {
if ($hashCashService->validateProcessFrom()) {
$required = ['salutation', 'firstname', 'lastname', 'email', 'message'];
if (!$this->getDocumentEditable('relations', 'topics')->isEmpty()) {
$required[] = 'topic';
}
if (!$this->getDocumentEditable('relations', 'regions')->isEmpty()) {
$required[] = 'region';
}
$params = array_merge($required, ['title', 'company', 'phone', 'gdpr-text', 'street', 'zip', 'city', 'country']);
unset($params['elhc_stamp']);
unset($params['elhc_difficulty']);
unset($params['elhc_nonce']);
foreach ($required as $param) {
if ($request->get($param) == '') {
$errors[$param] = 'missing';
} else if ($param == 'email' && !$mailValidator->isValid($request->get('email'), new RFCValidation())) {
$errors[$param] = 'invalid';
}
}
if (empty($errors)) {
$mailDoc = $this->getDocumentEditable('relation', 'email')->getElement();
if ($mailDoc instanceof Email) {
$mailParams = [];
foreach ($params as $param) {
$mailParams[$param] = $request->get($param);
}
array_filter($mailParams);
if ($mailParams['salutation']) {
$mailParams['salutation'] = $this->translator->trans($mailParams['salutation']);
}
$mailParams['items'] = ['salutation', ($this->getDocumentEditable('checkbox', 'use_company')?->isChecked() ? 'company' : 'title'), 'firstname', 'lastname', 'email', 'phone', 'street', 'zip', 'city', 'country', 'message'];
$mail = new Mail();
$mail->setDocument($mailDoc);
$mail->setParams($mailParams);
// calculate To address based on region and topic
$toAddress = false;
$region = isset($mailParams['region']) ? Region::getById($mailParams['region']) : null;
if (!$region instanceof Region) {
$region = $this->document->getProperty('region');
}
if ($topic = isset($mailParams['topic']) ? ContactTopic::getById($mailParams['topic']) : false) {
foreach ($topic->getEmailOverride() as $item) {
if ($item['email']->getData() != '' && $item['region']->getData() != '' && $item['region']->getData()->getId() == $region->getId()) {
$toAddress = $item['email']->getData();
break;
}
}
}
if (!$toAddress) {
$toAddress = $region->getContactEmail();
}
if ($mailValidator->isValid($toAddress, new RFCValidation())) {
$mail->addTo($toAddress);
$mail->send();
}
}
$successPage = $this->getDocumentEditable('relation', 'success')->getElement();
if ($successPage instanceof Page) {
return $this->redirect((string)$successPage);
}
$success = true;
} else {
$success = false;
}
} else {
$errors[] = 'hashcash not valid';
}
}
return $this->renderTemplate('Form/contact.html.twig', [
'success' => $success,
'errors' => $errors
]);
}
/**
* @param Request $request
* @param NewsletterService $newsletterService
* @param HashCashService $hashCashService
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Exception
*/
public function newsletterAction(Request $request, NewsletterService $newsletterService, HashCashService $hashCashService)
{
$errors = [];
if ($request->isMethod('post') && $request->get('potNumber') == '' && empty($request->get('ignore-post'))) {
if ($hashCashService->validateProcessFrom()) {
$params = $request->request->all();
unset($params['elhc_stamp']);
unset($params['elhc_difficulty']);
unset($params['elhc_nonce']);
$params['customerLanguage'] = $request->getLocale();
$selectedSegmentIds = $request->get('segments', []);
$selectedSegmentsArray = [];
if (is_array($selectedSegmentIds) && count($selectedSegmentIds)) {
$selectedSegments = new CustomerSegment\Listing();
$selectedSegments->addConditionParam('o_id IN (' . implode(',', $selectedSegmentIds) . ')');
$selectedSegmentsArray = $selectedSegments->load();
}
$nl_list = $this->getDocumentEditable('select', 'nl_list')->getData();
if (!in_array($nl_list, $newsletterService::ALLOWED_NEWSLETTER_LISTS)) {
$nl_list = $newsletterService::EVALANCHE_LIST;
}
//outsource allowed segments to experienceconfig
if ($request->get('numbirds')) {
if ($newsletterService->subscribeNumbirds($params['email'], $params, $selectedSegmentsArray, $this->getDocumentEditable('relations', 'segments')->getData())) {
$this->addNewsletterTrackingArray($params);
if ($this->getDocumentEditable('relation', 'success')->getData() && $this->getDocumentEditable('relation', 'success')->getData()['id']) {
$document = Document::getById($this->getDocumentEditable('relation', 'success')->getData()['id']);
if ($document) {
return $this->redirect($document);
}
}
return $this->redirect("?success=1");
}
} elseif ($newsletterService->subscribe($params['email'], $params, $nl_list, $selectedSegmentsArray, $this->getDocumentEditable('relations', 'segments')->getData(), $this->getDocumentEditable('relation', 'nl_attributeValue')->getElement() ?: null)) {
$this->addNewsletterTrackingArray($params);
if ($this->getDocumentEditable('relation', 'success')->getData() && $this->getDocumentEditable('relation', 'success')->getData()['id']) {
$document = Document::getById($this->getDocumentEditable('relation', 'success')->getData()['id']);
if ($document) {
return $this->redirect($document);
}
}
return $this->redirect("?success=1");
}
} else {
$errors[] = 'hashcash not valid';
}
}
return $this->renderTemplate('Form/newsletter.html.twig', [
'defaultPool' => $newsletterService::EVALANCHE_LIST,
'errors' => array_merge($errors, $newsletterService->getErrors() ?: [])
]);
}
public function brandCooperationAction(Request $request, HashCashService $hashCashService)
{
$errors = [];
$success = null;
$mailValidator = new EmailValidator();
if ($request->isMethod('POST') && $request->get('potNumber') == '') {
if ($hashCashService->validateProcessFrom()) {
$requiredFields = [
'company', 'contactPerson', 'street', 'zip', 'city', 'email', 'partnership'
];
$params = [
'message' => $request->get('message'),
'gdpr' => $request->get('gdpr-text'),
'phone' => $request->get('phone'),
'country' => $request->get('country'),
];
foreach ($requiredFields as $field) {
$params[$field] = $request->get($field);
if (empty($params[$field])) {
$errors[$field] = 'missing';
}
}
if (!empty($params['email']) && !$mailValidator->isValid($params['email'], new RFCValidation())) {
$errors['email'] = 'invalid';
}
if (empty($errors)) {
$adminMail = $this->getDocumentEditable('relation', 'notificationmail')->getElement();
$userMail = $this->getDocumentEditable('relation', 'usermail')->getElement();
if ($adminMail instanceof Email) {
$mail = new Mail();
$adminMailParams = $params;
$adminMailParams['items'] = array_keys($params);
try {
$mail->setParams($adminMailParams);
$mail->setDocument($adminMail);
$mail->send();
} catch (\Exception $e) {
$this->logger->error("Sending admin Mail failed\n" . $e->getMessage(), ['component' => self::COMPONENT]);
}
}
if ($userMail instanceof Email) {
$mail = new Mail();
try {
$mail->addTo($params['email']);
$mail->setDocument($userMail);
$mail->send();
} catch (\Exception $e) {
$this->logger->error("Sending user Mail failed\n" . $e->getMessage(), ['component' => self::COMPONENT]);
}
}
$successPage = $this->getDocumentEditable('relation', 'successPage')->getElement();
if ($successPage instanceof Page) {
return $this->redirect((string)$successPage->getFullPath());
}
} else {
$errors['hashcash'] = 'HashCash validation failed.';
}
}
return $this->renderTemplate('Form/brandCooperation.html.twig', [
'errors' => $errors,
'success' => $success
]);
}
return $this->renderTemplate('Form/brandCooperation.html.twig', [
'errors' => $errors,
'success' => $success
]);
}
protected function addNewsletterTrackingArray($params): void
{
$event = [
'event' => 'newsletter_signup',
'leadsUserData' => [
'address' => [
'sha256_first_name' => hash('sha256', $params['firstname'] ?? ''),
'sha256_last_name' => hash('sha256', $params['lastname'] ?? '')
],
'sha256_email_address' => hash('sha256', $params['email'])
]
];
$this->addFlash('trackingData', $event);
}
}