Files
cake-contact-us/src/Controller/Component/ContactUsComponent.php
T

301 lines
9.3 KiB
PHP
Raw Normal View History

2025-01-09 23:47:18 -08:00
<?php
declare(strict_types=1);
namespace CakeContactUs\Controller\Component;
use Cake\Controller\Component;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
2026-11-11 02:41:55 -08:00
use Cake\Event\EventInterface;
2025-01-09 23:47:18 -08:00
use Cake\Http\Response;
use Cake\I18n\DateTime;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use CakeContactUs\CakeContactUsPlugin;
use CakeContactUs\Model\Table\ContactUsFormSubmissionsTable;
2025-01-09 23:47:18 -08:00
/**
* ContactUs component
*
* @property \Cake\Controller\Component\FlashComponent $Flash
2025-01-09 23:47:18 -08:00
*/
class ContactUsComponent extends Component {
2025-01-09 23:47:18 -08:00
/**
* @var \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable|\Cake\ORM\Table
*/
protected ContactUsFormSubmissionsTable|Table $ContactUsFormSubmissions;
/**
2025-01-09 23:47:18 -08:00
* Default configuration.
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [];
2025-01-09 23:47:18 -08:00
/**
2025-01-09 23:47:18 -08:00
* @var array|string[]
*/
protected array $components = ['Flash'];
2025-01-09 23:47:18 -08:00
2026-11-11 02:41:55 -08:00
/**
* Get the Controller callbacks this Component is interested in.
*
* Uses Conventions to map controller events to standard component
* callback method names. By defining one of the callback methods a
* component is assumed to be interested in the related event.
*
* Override this method if you need to add non-conventional event listeners.
* Or if you want components to listen to non-standard events.
*
* @return array<string, mixed>
*/
public function implementedEvents(): array {
$eventMap = [
'Controller.initialize' => 'beforeFilter',
'Controller.startup' => 'startup',
'Controller.beforeRender' => 'beforeRender',
'Controller.beforeRedirect' => 'beforeRedirect',
'Controller.shutdown' => 'afterFilter',
CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED => 'beforeFormSaved',
];
$events = [];
foreach ($eventMap as $event => $method) {
if (method_exists($this, $method)) {
$events[$event] = $method;
}
}
return $events;
}
/**
2025-01-09 23:47:18 -08:00
* @param array $config
* @throws \Exception
2025-01-09 23:47:18 -08:00
* @return void
*
*/
public function initialize(array $config): void {
parent::initialize($config); // TODO: Change the autogenerated stub
2025-01-09 23:47:18 -08:00
$this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions');
2025-01-09 23:47:18 -08:00
$requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha');
2026-11-14 01:54:14 -08:00
$useTurnstile = Configure::read('ContactUs.turnstile', [
'enabled' => false,
]);
$this->setConfig('redirectUrl', Configure::read('ContactUs.redirectUrl', '/'));
$this->setConfig('addIdToRedirect', Configure::read('ContactUs.addIdToRedirect', false));
$this->setConfig('requireEmail', Configure::readOrFail('ContactUs.fields.email'));
$this->setConfig('requireCaptcha', $requireCaptcha);
2026-11-11 02:41:55 -08:00
$this->setConfig('turnstile', $useTurnstile);
if ($requireCaptcha) {
$this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']);
}
2026-11-14 01:54:14 -08:00
if ($useTurnstile['enabled'] ?? false) {
// $this->getController()->viewBuilder()->addHelpers(['Turnstile']);
2026-11-11 02:41:55 -08:00
}
}
2025-01-09 23:47:18 -08:00
/**
* @return \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission
2025-01-09 23:47:18 -08:00
*/
public function newContactUsForm() {
if ($this->getConfig('requireCaptcha') && PHP_SAPI !== 'cli') {
$this->ContactUsFormSubmissions->addBehavior('Captcha.Captcha');
}
2025-11-10 22:26:52 -08:00
return $this->ContactUsFormSubmissions->newEmptyEntity();
}
2025-01-09 23:47:18 -08:00
/**
2026-01-28 02:02:30 -08:00
* @param \Cake\Datasource\EntityInterface $contactUsFormSubmission
* @param array|null $postData
* @return \Cake\Http\Response|null|void
2025-01-09 23:47:18 -08:00
*/
public function processContactUsForm(EntityInterface $contactUsFormSubmission, array|null $postData) {
if (!isset($postData)) {
$postData = $this->getController()->getRequest()->getData();
}
2026-11-11 02:41:55 -08:00
$postData['client_ip'] = $this->_getIp();
$postData['submitted_at'] = DateTime::now();
2026-11-11 02:41:55 -08:00
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
$this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]);
2025-01-09 23:47:18 -08:00
$event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED, [
'contactUsFormSubmission' => $contactUsFormSubmission,
], $this->getController());
$result = $event->getResult();
if ($event->isStopped()) {
2026-11-11 02:41:55 -08:00
if ($result['redirect'] ?? false) {
return $this->getController()->redirect($result['redirect']);
}
$message = __d('cake_contact_us', 'Verification failed. Please try again.');
$this->Flash->error($message);
return;
}
2025-01-09 23:47:18 -08:00
2026-11-11 02:41:55 -08:00
if ($result instanceof EntityInterface) {
$final = $this->_finishSave($contactUsFormSubmission);
if ($final instanceof EntityInterface) { // validation failed
$this->getController()->set(['contactUsFormSubmission' => $final]);
2025-11-10 22:26:52 -08:00
2026-11-11 02:41:55 -08:00
return;
}
return $final;
}
2025-11-10 22:26:52 -08:00
2026-11-11 02:41:55 -08:00
$final = $this->_finishSave($contactUsFormSubmission);
if ($final instanceof EntityInterface) {
// @TODO contact us form submission failed - handle here
$message = __d('cake_contact_us', 'Something doesn\'t look quite right. Please try again.');
2025-01-09 23:47:18 -08:00
2026-11-11 02:41:55 -08:00
$this->Flash->error($message);
// @TODO contact us form submission failed - handle here
$this->getController()->set(['contactUsFormSubmission' => $final]);
return;
}
return $final;
}
2025-01-09 23:47:18 -08:00
/**
2025-01-09 23:47:18 -08:00
* Prepare flash messages after registration, and dispatch afterRegister event
*
* @param \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmissionSaved Contact us form submission entity
2025-01-09 23:47:18 -08:00
* @return \Cake\Http\Response
*/
protected function _afterFormSaved(EntityInterface $contactUsFormSubmissionSaved) {
$message = __d('cake_contact_us', 'Message received, thank you. We will be in touch soon.');
$event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED, [
'contactUsFormSubmission' => $contactUsFormSubmissionSaved,
], $this->getController());
$result = $event->getResult();
if ($result instanceof Response) {
return $result;
}
$this->Flash->success($message);
$redirectUrl = $this->getConfig('redirectUrl');
if ($this->getConfig('addIdToRedirect')) {
$redirectUrl[] = $contactUsFormSubmissionSaved->get($this->ContactUsFormSubmissions->getPrimaryKey());
}
return $this->getController()->redirect($redirectUrl);
}
2025-01-09 23:47:18 -08:00
2026-11-11 02:41:55 -08:00
/**
* @return void
*/
public function beforeFormSaved(EventInterface $event) {
if (!$this->getConfig('turnstile')) {
return;
}
$siteKey = getenv(CakeContactUsPlugin::CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SITE_KEY) ?: $this->getConfig('turnstile.siteKey');
$secretKey = getenv(CakeContactUsPlugin::CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SECRET_KEY) ?: $this->getConfig('turnstile.secretKey');
2026-11-14 01:54:14 -08:00
if (!$siteKey || !$secretKey) {
2026-11-11 02:41:55 -08:00
$event->stopPropagation();
$event->setResult([
'success' => false,
'error-codes' => ['missing-turnstile-site-configuration'],
]);
return;
}
$entity = $event->getData('contactUsFormSubmission');
$token = $entity->get('cf-turnstile-response') ?: $this->getController()->getRequest()->getData('cf-turnstile-response');
if (!$token) {
$event->stopPropagation();
$event->setResult([
'success' => false,
'error-codes' => ['missing-token'],
]);
return;
}
$turnstileValidation = $this->_validateTurnstile(
$token,
$entity->get('client_ip') ?? $this->_getIp(),
);
if ($turnstileValidation['success'] ?? false) {
return; // good to proceed
}
$event->stopPropagation();
$event->setResult($turnstileValidation);
}
/**
* @return string -
*/
protected function _getIp() {
if ($this->getConfig('clientIpHeader')) {
2026-11-11 03:32:10 -08:00
return $this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader'))
?: $this->getController()->getRequest()->clientIp();
2026-11-11 02:41:55 -08:00
}
return $this->getController()->getRequest()->clientIp();
}
/**
* @param \Cake\Datasource\EntityInterface $contactUsFormSubmission
*
* @return \Cake\Datasource\EntityInterface|\Cake\Http\Response
*/
protected function _finishSave(EntityInterface $contactUsFormSubmission) {
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
}
return $contactUsFormSubmission; // has errors - return entity
}
/**
* @param string $token
* @param string|null $remoteIp
*
* @return array
*/
protected function _validateTurnstile(string $token, string|null $remoteIp = null): array {
// if (PHP_SAPI === 'cli') {
// return ['success' => true];
// }
$url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$data = [
'secret' => $this->getConfig('turnstile.secretKey'),
'response' => $token,
];
if ($remoteIp) {
$data['remoteip'] = $remoteIp;
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($response === false || $error !== '') {
return ['success' => false, 'error-codes' => ['internal-error']];
}
return json_decode($response, true);
}
2025-01-09 23:47:18 -08:00
}