Files
kupshop/bundles/KupShop/UserBundle/View/UserView.php
2025-08-02 16:30:27 +02:00

502 lines
16 KiB
PHP

<?php
namespace KupShop\UserBundle\View;
use KupShop\ContentBundle\Util\Captcha;
use KupShop\ContentBundle\View\Exception\ValidationException;
use KupShop\GraphQLBundle\EventListener\JsShopRefreshListener;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Email\UserRegisterEmail;
use KupShop\KupShopBundle\Exception\RedirectException;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Mail\EmailCheck;
use KupShop\KupShopBundle\Views\Traits\RequestTrait;
use KupShop\KupShopBundle\Views\View;
use KupShop\OrderingBundle\Util\VIES\DICValidator;
use KupShop\UserBundle\Util\UserConsent;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class UserView extends View
{
use RequestTrait;
protected string $smartyFallback = 'account';
protected string $entrypoint = 'account';
protected $template = 'user.tpl';
private $type;
protected $user;
protected $register;
protected $error;
public function __construct(
protected UserConsent $userConsent,
protected EmailCheck $emailCheck,
protected DICValidator $DICValidator,
protected UserRegisterEmail $email,
protected SessionInterface $session,
protected RequestStack $requestStack,
) {
$this->user = new \User();
}
public function getTitle()
{
if ($this->newUser()) {
return translate('title', 'user')[0];
}
return translate('title', 'user')[1];
}
public function getBreadcrumbs()
{
if ($this->newUser()) {
return getReturnNavigation(-1, 'NO_TYPE', [translate('title', 'user')[0]]);
}
return getReturnNavigation(-1, 'USER', [translate('title', 'user')[1]]);
}
public function getBodyVariables()
{
$vars = parent::getBodyVariables();
if ($this->newUser()) {
$vars['newUser'] = true;
}
if ($this->request->get('Submit')) {
$this->handleSubmit();
}
// data to template
if (!$this->newUser() || $this->request->get('Submit')) {
$data = $this->getData();
foreach ($data as $key => $value) {
$vars['input'][$key] = ['value' => $value];
}
}
$vars['input']['news'] = getVal('news', null, $this->newUser() == true ? 'N' : $data['news']);
$vars['input']['password']['value'] = '';
return $vars;
}
private function addFieldsToInvoice($invoice, $fields)
{
foreach ($fields as $field) {
$invoice[$field] = getVal($field);
}
return $invoice;
}
protected function getInvoice()
{
$fields = \User::getFields();
$invoice = [];
foreach ($fields as $field) {
$invoice[$field] = getVal($field);
}
return $invoice;
}
protected function getDelivery()
{
$fields = \User::getFields();
$delivery = [];
foreach ($fields as $field) {
$delivery[$field] = getVal('d'.$field);
}
return $delivery;
}
protected function sendConfirmEmail(\User $user)
{
$this->email->setUser($user);
$message = $this->email->getEmail();
$message['to'] = $user->email;
return $this->email->sendEmail($message);
}
protected function handleSubmit(): void
{
$invoice = $this->getInvoice();
$invoice = $this->addFieldsToInvoice($invoice, ['email', 'ico', 'dic', 'phone', 'transport', 'gender', 'birthdate', 'copy_email']);
$delivery = $this->getDelivery();
$password = getVal('password');
$newsletter = getVal('news', null, 'N');
foreach (getVal('custom_data', null, []) as $key => $value) {
$this->user->setCustomData($key, $value);
}
if ($this->newUser()) {
if ($invoice['email'] && $this->emailCheck->isEmailDomainValid($invoice['email'])) {
if ($this->checkCaptcha()) {
// check DIC
$error = false;
if (findModule(\Modules::ORDERS, \Modules::SUB_DIC_VALIDATE)) {
if (!empty($invoice['dic'])) {
if (!$this->DICValidator->checkVat($invoice['dic'])) {
addUserMessage(translate('invalid_dic', 'order_error'), 'danger');
$error = true;
}
}
}
if (!$error) {
// transakce kvuli master / slave
$user = sqlGetConnection()->transactional(function () use ($invoice, $delivery, $password, $newsletter) {
$id = $this->registerUser($invoice, $delivery, $password);
if (!$id) {
return null;
}
// newsletter save
$this->userConsent->updateNewsletter($id, $newsletter, $this->newUser(), $this->isNewsletterConfirmed());
// login user
$userObject = \User::createFromId($id);
$userObject->login(getUserKey());
return $userObject;
});
if ($user) {
// send confirm email
$this->sendConfirmEmail($user);
// redirect on homepage
addUserMessage(translate('registerSucceeded', 'user'), 'success');
$this->requestStack->getMainRequest()->attributes->set('gtm_registration', [
'email' => $invoice['email'],
'firstname' => $invoice['name'],
]);
if (findModule(\Modules::JS_SHOP)) {
$this->session->set(JsShopRefreshListener::SESSION_NAME, true);
}
$path = $this->request->get('redirect') ? $this->request->get('redirect') : path('account');
throw new RedirectException($path);
}
}
}
} else {
addUserMessage(sprintf(translate('error', 'user')['invalid_email_domain'], htmlentities($invoice['email'])));
}
} else {
$oldUserEmail = \User::getCurrentUser()->email;
// update
$id = $this->updateUser($invoice, $delivery);
if ($id) {
// newsletter save
$this->userConsent->updateNewsletter($id, $newsletter, $this->newUser(), $this->isNewsletterConfirmed());
// password update
if (!empty($password)) {
$this->user->updatePassword($password);
}
if (!empty($password) || $oldUserEmail != $invoice['email']) {
// relogin user, otherwise it might not be recognized on the next request
$userObject = \User::createFromId($id);
$userObject->login(getUserKey());
}
addUserMessage(translate('error', 'user')['saved'], 'success');
// redirect on homepage
redirection('REFERER');
}
}
}
protected function getData()
{
$id_user = Contexts::get(UserContext::class)->getActiveId();
$data = [];
$qb = sqlQueryBuilder()->select('*')
->from('users')
->where('id=:id')->setParameter('id', $id_user)->execute();
if ($qb->rowCount() == 1) {
$user = $qb->fetch();
$data = $this->fetchUserData($data, $user);
return $data;
}
// collect post data
foreach ($this->request->request->all() as $name => $value) {
$data[$name] = $value;
}
return $data;
}
protected function checkPassword($password, $passwordAgain)
{
if ($password == $passwordAgain) {
return true;
}
return false;
}
protected function updateUser($invoice, $delivery)
{
try {
$this->updateAddresses($invoice, $delivery);
} catch (ValidationException $e) {
$this->addErrorMessage($e->getMessage());
return false;
}
if ($this->error) {
$this->addError();
return false;
}
$oldUserEmail = \User::getCurrentUser()->email;
if ($oldUserEmail != $invoice['email']) {
$this->user->id = null;
$this->error = $this->user->sanitizeRegistration();
if ($this->error == 15) { // login_exists
$this->error = 20; // login_exists_edit
}
}
if (!$this->error) {
$id = $this->user->update();
// id of registered user
return $id;
} else {
$this->addError();
return false;
}
}
protected function registerUser($invoice, $delivery, $password)
{
if (Contexts::get(UserContext::class)->isActive()) {
return Contexts::get(UserContext::class)->getActiveId();
}
try {
$this->updateAddresses($invoice, $delivery);
} catch (ValidationException $e) {
$this->addErrorMessage($e->getMessage());
return false;
}
if ($this->error) {
$this->addError();
return false;
}
$this->error = $this->prepareRegister($password);
if (!$this->error) {
$id = $this->user->update();
$this->user->updatePassword($this->register);
// id of registered user
return $id;
} else {
$this->addError();
return false;
}
}
protected function addError()
{
switch ($this->error) {
case 1:
addUserMessage(translate('error', 'user')['not_all_valid']);
break;
case 2:
addUserMessage(replacePlaceholders(
translate('error', 'user')['login_exists'],
['URL' => path('kupshop_user_login_login')]
));
break;
case 3:
addUserMessage(translate('error', 'user')['false_length_passw']);
break;
case 4:
addUserMessage(translate('error', 'user')['failed']);
break;
case 5:
addUserMessage(translate('error', 'user')['saved']);
break;
case 6:
addUserMessage(translate('error', 'user')['missing_name_invoice']);
break;
case 7:
addUserMessage(translate('error', 'user')['missing_street_invoice']);
break;
case 8:
addUserMessage(translate('error', 'user')['missing_city_invoice']);
break;
case 9:
addUserMessage(translate('error', 'user')['missing_zip_invoice']);
break;
case 10:
addUserMessage(translate('error', 'user')['missing_email_invoice']);
break;
case 11:
addUserMessage(translate('error', 'user')['missing_phone_invoice']);
break;
case 12:
addUserMessage(translate('error', 'user')['false_email']);
break;
case 13:
addUserMessage(translate('error', 'user')['false_zip']);
break;
case 14:
addUserMessage(translate('error', 'user')['false_phone']);
break;
case 15:
addUserMessage(replacePlaceholders(
translate('error', 'user')['login_exists'],
['URL' => path('kupshop_user_login_login')]
));
break;
case 16:
addUserMessage(translate('error', 'user')['false_length_passw']);
break;
case 20:
addUserMessage(translate('error', 'user')['login_exists_edit']);
break;
}
}
protected function prepareRegister($password)
{
$this->register = false;
$error = $this->user->sanitizeRegistration($password);
if (!$error) {
$this->register = $password;
}
return $error;
}
protected function isNewsletterConfirmed(): bool
{
return false;
}
public function newUser()
{
if ($this->getType() == 'new') {
return true;
}
return false;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
}
public function setUserId($userId): self
{
$this->user->id = $userId;
return $this;
}
protected function checkCaptcha(): bool
{
// Check CAPTCHA
if (findModule('recaptcha', 'registration')) {
try {
Captcha::checkCaptcha();
} catch (ValidationException $e) {
$this->addErrorMessage($e->getMessage());
return false;
}
}
return true;
}
protected function fetchUserData($data, $user)
{
$data['password'] = '';
$data['name'] = $user['name'];
$data['surname'] = $user['surname'];
$data['firm'] = $user['firm'];
$data['street'] = $user['street'];
$data['city'] = $user['city'];
$data['zip'] = $user['zip'];
$data['country'] = $user['country'];
$data['state'] = $user['state'];
$data['custom_address'] = $user['custom_address'];
// ------------------------------
$data['dname'] = $user['delivery_name'];
$data['dsurname'] = $user['delivery_surname'];
$data['dfirm'] = $user['delivery_firm'];
$data['dstreet'] = $user['delivery_street'];
$data['dcity'] = $user['delivery_city'];
$data['dzip'] = $user['delivery_zip'];
$data['dcountry'] = $user['delivery_country'];
$data['dstate'] = $user['delivery_state'];
$data['dcustom_address'] = $user['delivery_custom_address'];
$data['dphone'] = $user['delivery_phone'];
$data['demail'] = $user['delivery_email'];
// ------------------------------
$data['email'] = $user['email'];
$data['ico'] = $user['ico'];
$data['dic'] = $user['dic'];
$data['copy_email'] = $user['copy_email'];
$data['phone'] = $user['phone'];
$data['mobile'] = $user['mobile'];
$data['fax'] = $user['fax'];
$data['gender'] = $user['gender'];
$data['birthdate'] = $user['birthdate'];
$data['accountNo'] = $user['account_no'];
$data['accountBank'] = $user['account_bank'];
$data['accountSymbol'] = $user['account_symbol'];
$data['news'] = $user['get_news'];
$data['transport'] = $user['prefer_transport'];
$data['date_subscribe'] = $user['date_subscribe'];
$data['date_unsubscribe'] = $user['date_unsubscribe'];
$data['custom_data'] = json_decode($user['custom_data'], true);
return $data;
}
protected function updateAddresses($invoice, $delivery): void
{
$this->error = $this->user->updateAddresses($invoice, $delivery);
}
}