*/ protected array $_defaultConfig = []; /** * @var array|string[] */ protected array $components = ['Flash']; /** * 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 */ 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; } /** * @param array $config * @throws \Exception * @return void * */ public function initialize(array $config): void { parent::initialize($config); // TODO: Change the autogenerated stub $this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions'); $requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha'); $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); $this->setConfig('turnstile', $useTurnstile); if ($requireCaptcha) { $this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']); } if ($useTurnstile['enabled'] ?? false) { // $this->getController()->viewBuilder()->addHelpers(['Turnstile']); } } /** * @return \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission */ public function newContactUsForm() { if ($this->getConfig('requireCaptcha') && PHP_SAPI !== 'cli') { $this->ContactUsFormSubmissions->addBehavior('Captcha.Captcha'); } return $this->ContactUsFormSubmissions->newEmptyEntity(); } /** * @param \Cake\Datasource\EntityInterface $contactUsFormSubmission * @param array|null $postData * @return \Cake\Http\Response|null|void */ public function processContactUsForm(EntityInterface $contactUsFormSubmission, array|null $postData) { if (!isset($postData)) { $postData = $this->getController()->getRequest()->getData(); } $postData['client_ip'] = $this->_getIp(); $postData['submitted_at'] = DateTime::now(); $contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData); $this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]); $event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED, [ 'contactUsFormSubmission' => $contactUsFormSubmission, ], $this->getController()); $result = $event->getResult(); if ($event->isStopped()) { 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; } if ($result instanceof EntityInterface) { $final = $this->_finishSave($contactUsFormSubmission); if ($final instanceof EntityInterface) { // validation failed $this->getController()->set(['contactUsFormSubmission' => $final]); return; } return $final; } $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.'); $this->Flash->error($message); // @TODO contact us form submission failed - handle here $this->getController()->set(['contactUsFormSubmission' => $final]); return; } return $final; } /** * Prepare flash messages after registration, and dispatch afterRegister event * * @param \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmissionSaved Contact us form submission entity * @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); } /** * @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'); if (!$siteKey || !$secretKey) { $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')) { return $this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader')) ?: $this->getController()->getRequest()->clientIp(); } 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); } }