vendor/uvdesk/support-center-bundle/Controller/Customer.php line 95

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\SupportCenterBundle\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\Security\Core\Security;
  5. use Webkul\UVDesk\SupportCenterBundle\Entity as SupportEntities;
  6. use Webkul\UVDesk\CoreFrameworkBundle\Entity as CoreEntities;
  7. use Webkul\UVDesk\CoreFrameworkBundle\Form\UserProfile;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. use Webkul\UVDesk\CoreFrameworkBundle\Utils\TokenGenerator;
  11. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  12. use Webkul\UVDesk\CoreFrameworkBundle\FileSystem\FileSystem;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use Symfony\Component\Filesystem\Filesystem as Fileservice;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Webkul\UVDesk\CoreFrameworkBundle\Services as CoreServices;
  17. use Webkul\UVDesk\CoreFrameworkBundle\Providers\UserProvider;
  18. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  19. Class Customer extends AbstractController
  20. {
  21.     private $translator;
  22.     private $fileSystem;
  23.     private $passwordEncoder;
  24.     private $fileUploadService;
  25.     private $uvdeskService;
  26.     private $userProvider;
  27.     public function __construct(TranslatorInterface $translatorUserPasswordEncoderInterface $passwordEncoderFileSystem $fileSystemCoreServices\FileUploadService $fileUploadServiceCoreServices\EmailService $emailServiceCoreServices\UVDeskService $uvdeskServiceUserProvider $userProvider)
  28.     {
  29.         $this->translator $translator;
  30.         $this->fileSystem $fileSystem;
  31.         $this->passwordEncoder $passwordEncoder;
  32.         $this->fileUploadService $fileUploadService;
  33.         $this->emailService $emailService;
  34.         $this->uvdeskService $uvdeskService;
  35.         $this->userProvider $userProvider;
  36.     }
  37.     protected function redirectUserToLogin()
  38.     {
  39.         $authChecker $this->container->get('security.authorization_checker');
  40.         if ($authChecker->isGranted('ROLE_CUSTOMER'))
  41.             return true;
  42.     }
  43.     protected function isWebsiteActive()
  44.     {
  45.         $entityManager $this->getDoctrine()->getManager();
  46.         $website $entityManager->getRepository(CoreEntities\Website::class)->findOneByCode('knowledgebase');
  47.   
  48.         if (! empty($website)) {
  49.             $knowledgebaseWebsite $entityManager->getRepository(SupportEntities\KnowledgebaseWebsite::class)->findOneBy(['website' => $website->getId(), 'status' => 1]);
  50.             
  51.             if (! empty($knowledgebaseWebsite) && true == $knowledgebaseWebsite->getIsActive()) {
  52.                 return true;
  53.             }
  54.         }
  55.         $this->noResultFound();
  56.     }
  57.     protected function noResultFound()
  58.     {
  59.         throw new NotFoundHttpException('Permission Denied !');
  60.     }
  61.     protected function isLoginDisabled()
  62.     {
  63.         $entityManager $this->getDoctrine()->getManager();
  64.         $website $entityManager->getRepository(CoreEntities\Website::class)->findOneByCode('knowledgebase');
  65.         if (! empty($website)) {
  66.             $configuration $entityManager->getRepository(SupportEntities\KnowledgebaseWebsite::class)->findOneBy([
  67.                 'website' => $website->getId(),
  68.                 'isActive' => 1,
  69.             ]);
  70.             if (
  71.                 ! empty($configuration
  72.                 && $configuration->getDisableCustomerLogin()
  73.             ) {
  74.                 return true;
  75.             }
  76.         }
  77.         return false;
  78.     }
  79.     public function loginOtpVerify(Request $request) {
  80.         $params $request->request->all();
  81.         $entityManager $this->getDoctrine()->getManager();
  82.         if (empty($params['_username'])) {
  83.             return new JsonResponse([
  84.                 'success' => false,
  85.                 'message' => "No user details provided. Please try again later.",
  86.             ], 403);
  87.         }
  88.         $user $entityManager->getRepository(CoreEntities\User::class)->findOneByEmail($params['_username']);
  89.         if (empty($user) || empty($params['otp'])) {
  90.             return new JsonResponse([
  91.                 'success' => false,
  92.                 'message' => "No associated user account details were found. Please try again later.",
  93.             ], 403);
  94.         } else if ($user->getVerificationCode() != $params['otp']) {
  95.             return new JsonResponse([
  96.                 'success' => false,
  97.                 'message' => "Invalid OTP provided. Please try again later.",
  98.             ], 403);
  99.         }
  100.         $currentTimestamp = new \DateTime('now');
  101.         $lastOtpGeneratedAtTimestamp $user->getLastOtpGeneratedAt();
  102.         $lastOtpGeneratedAtTimestamp->modify('+5 minutes');
  103.         $interval $lastOtpGeneratedAtTimestamp->diff($currentTimestamp);
  104.         $isTimePeriodElapsed = (bool) $interval->invert false true;
  105.         if ($isTimePeriodElapsed == true) {
  106.             return new JsonResponse([
  107.                 'success' => false,
  108.                 'message' => "The provided OTP has expired. Please try again later.",
  109.             ], 403);
  110.         }
  111.         $user $this->userProvider->refreshUser($user);
  112.         try {
  113.             $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  114.             $this->container->get('security.token_storage')->setToken($token);
  115.             // Regenerate the session
  116.             $request->getSession()->migrate();
  117.             $this->addFlash('success'$this->translator->trans('Success ! Logged in successfully.'));
  118.             return new JsonResponse([
  119.                 'success' => true,
  120.                 'message' => "Successfully logged in.",
  121.             ]);
  122.         } catch (\Exception $e) {
  123.             return new JsonResponse([
  124.                 'success' => false,
  125.                 'message' => "Failed to login " $e->getMessage() ,
  126.             ], 403);
  127.         }
  128.     }
  129.     public function generateOtp(Request $request) {
  130.         $params $request->request->all();
  131.         $entityManager $this->getDoctrine()->getManager();
  132.         $website $entityManager->getRepository(CoreEntities\Website::class)->findOneByCode('helpdesk');
  133.         $knowledgebase $entityManager->getRepository(CoreEntities\Website::class)->findOneByCode('knowledgebase');
  134.         $user $entityManager->getRepository(CoreEntities\User::class)->retrieveHelpdeskCustomerInstances($params['_username']);
  135.         if (empty($user)) {
  136.             return new JsonResponse([
  137.                 'success' => false,
  138.                 'message' => "No associated user accounts were found with the email '{$params['_username']}'.",
  139.             ], 403);
  140.         } else if ($this->isLoginDisabled()) {
  141.             return new JsonResponse([
  142.                 'success' => false,
  143.                 'message' => "Login has been disabled for this helpdesk.",
  144.             ], 403);
  145.         }
  146.         $currentTimestamp = new \DateTime('now');
  147.         $lastOtpGeneratedAtTimestamp $user->getLastOtpGeneratedAt();
  148.         if (! empty($lastOtpGeneratedAtTimestamp)) {
  149.             $lastOtpGeneratedAtTimestamp->modify('+1 minute');
  150.             $interval $lastOtpGeneratedAtTimestamp->diff($currentTimestamp);
  151.             $isTimePeriodElapsed = (bool) $interval->invert false true;
  152.             if ($isTimePeriodElapsed == false) {
  153.                 return new JsonResponse([
  154.                     'success' => false,
  155.                     'message' => "Please wait for upto 1 minute before requesting a new OTP.",
  156.                 ]);
  157.             }
  158.         }
  159.         $user->setVerificationCode(TokenGenerator::generateToken(6$range '0123456789'))
  160.             ->setLastOtpGeneratedAt(new \DateTime('now'))
  161.         ;
  162.         $entityManager->persist($user);
  163.         $entityManager->flush();
  164.         $name ucwords(trim(implode(' ', [$user->getFirstName(), $user->getLastName()])));
  165.         // Generate email content
  166.         $subject "Login OTP from ".$website->getName();
  167.         $content $this->renderView('@UVDeskSupportCenter/CustomerLogin/customer-login-otp-verification-email.html.twig', [
  168.             'name'             => $name,
  169.             'verificationCode' => $user->getVerificationCode(),
  170.             'helpdeskName'     => $website->getName(),
  171.             'helpdeskMail'     => $this->getParameter('uvdesk.support_email.id'),
  172.             'helpdeskLogo'     => $knowledgebase->getLogo() ? $this->uvdeskService->generateCompleteLocalResourcePathUri($knowledgebase->getLogo()) : "",
  173.         ]);
  174.         $this->emailService->sendMail($subject$content$user->getEmail());
  175.         return new JsonResponse([
  176.             'success' => true,
  177.             'message' => "Please check your email for a OTP verification code.",
  178.         ]);
  179.     }
  180.     public function login(Request $request)
  181.     {
  182.         $this->isWebsiteActive();
  183.         if ($this->redirectUserToLogin()) {
  184.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket_collection')); // Replace with Dashboard route
  185.         }
  186.         /** check disabled customer login **/
  187.         if ($this->isLoginDisabled()) {
  188.             $this->addFlash('warning'$this->translator->trans('Warning ! Customer Login disabled by admin.') );
  189.             
  190.             return $this->redirect($this->generateUrl('helpdesk_knowledgebase'));
  191.         }
  192.         $session $request->getSession();
  193.         $error $session->get(Security::AUTHENTICATION_ERROR);
  194.         $session->remove(Security::AUTHENTICATION_ERROR);
  195.         if ($error) {
  196.             $this->addFlash('warning'$this->translator->trans('Warning ! ' $error->getMessage()) );
  197.         }
  198.         return $this->render('@UVDeskSupportCenter/CustomerLogin/customer-login.html.twig', [
  199.             'searchDisable' => true,
  200.             'last_username' => $session->get(Security::LAST_USERNAME),
  201.             'error'         => $error,
  202.             'breadcrumbs' => [
  203.                 [
  204.                     'label' => $this->translator->trans('Support Center'),
  205.                     'url'   => $this->generateUrl('helpdesk_knowledgebase')
  206.                 ], [
  207.                     'label' => $this->translator->trans('Sign In'),
  208.                     'url'   => '#'
  209.                 ]
  210.             ]
  211.         ]);
  212.     }
  213.     public function Account(Request $request)
  214.     {
  215.         $this->isWebsiteActive();
  216.         $em $this->getDoctrine()->getManager();
  217.         $user $this->getUser();
  218.         $errors = [];
  219.         if ($request->getMethod() == 'POST') {
  220.             $data     $request->request->all();
  221.             $dataFiles $request->files->get('user_form');
  222.             $data $data['user_form'];
  223.             // Profile upload validation
  224.             $validMimeType = ['image/jpeg''image/png''image/jpg'];
  225.             if (isset($dataFiles['profileImage'])) {
  226.                 if (! in_array($dataFiles['profileImage']->getMimeType(), $validMimeType)) {
  227.                     $this->addFlash('warning'$this->translator->trans('Error ! Profile image is not valid, please upload a valid format'));
  228.                     
  229.                     return $this->redirect($this->generateUrl('helpdesk_customer_account'));
  230.                 }
  231.             }
  232.             $checkUser $em->getRepository(CoreEntities\User::class)->findOneBy(array('email'=>$data['email']));
  233.             $errorFlag 0;
  234.             if ($checkUser) {
  235.                 if ($checkUser->getId() != $user->getId())
  236.                     $errorFlag 1;
  237.             }
  238.             if (! $errorFlag) {
  239.                 $password $user->getPassword();
  240.                 $form $this->createForm(UserProfile::class, $user);
  241.                 $form->handleRequest($request);
  242.                 $form->submit($data);
  243.                 if ($form->isValid()) {
  244.                     if ($data != null && (!empty($data['password']['first']))) {
  245.                         $encodedPassword $this->passwordEncoder->encodePassword($user$data['password']['first']);
  246.                         if (! empty($encodedPassword) ) {
  247.                             $user->setPassword($encodedPassword);
  248.                         }
  249.                     } else {
  250.                         $user->setPassword($password);
  251.                     }
  252.                     $user->setFirstName($data['firstName']);
  253.                     $user->setLastName($data['lastName']);
  254.                     $user->setEmail($data['email']);
  255.                     $user->setTimeZone($data['timezone']);
  256.                     $user->setTimeFormat($data['timeformat']);
  257.                     
  258.                     $em->persist($user);
  259.                     $em->flush();
  260.                     $userInstance $em->getRepository(CoreEntities\UserInstance::class)->findOneBy(array('user' => $user->getId()));
  261.                     if (isset($dataFiles['profileImage'])) {
  262.                         $previousImage $userInstance->getProfileImagePath();
  263.                         if ($previousImage != null) {
  264.                             $image str_replace("\\","/",$this->getParameter('kernel.project_dir').'/public'.$previousImage);
  265.                             $check $this->fileUploadService->fileRemoveFromFolder($image); 
  266.                         }
  267.                         $assetDetails $this->fileSystem->getUploadManager()->uploadFile($dataFiles['profileImage'], 'profile');
  268.                         $userInstance->setProfileImagePath($assetDetails['path']);
  269.                     }
  270.                     // Removed profile image from database and path
  271.                     $fileService = new Fileservice;
  272.                     if ($request->get('removeImage') == 'on') {
  273.                         if ($userInstance->getProfileImagePath()) {
  274.                             $fileService->remove($this->getParameter('kernel.project_dir').'/public'.$userInstance->getProfileImagePath());
  275.                         }
  276.                         $userInstance $userInstance->setProfileImagePath(null);
  277.                     }
  278.                     $userInstance  $userInstance->setContactNumber($data['contactNumber']);
  279.                     $em->persist($userInstance);
  280.                     $em->flush();
  281.                     $this->addFlash('success'$this->translator->trans('Success ! Profile updated successfully.'));
  282.                     return $this->redirect($this->generateUrl('helpdesk_customer_account'));
  283.                 } else {
  284.                     $errors $form->getErrors();
  285.                     $errors $this->getFormErrors($form);
  286.                 }
  287.             } else {
  288.                 $this->addFlash('warning'$this->translator->trans('Error ! User with same email is already exist.'));
  289.                 return $this->redirect($this->generateUrl('helpdesk_customer_account'));
  290.             }
  291.         }
  292.         return $this->render('@UVDeskSupportCenter/Knowledgebase/customerAccount.html.twig', [
  293.             'searchDisable' => true,
  294.             'user'          => $user,
  295.         ]);
  296.     }
  297.     public function searchArticle(Request $request)
  298.     {
  299.         $this->isWebsiteActive();
  300.         $searchQuery $request->query->get('s');
  301.         if (empty($searchQuery)) {
  302.             return $this->redirect($this->generateUrl('helpdesk_customer_ticket_collection'));
  303.         }
  304.         $articleCollection $this->getDoctrine()->getRepository(SupportEntities\Article::class)->getArticleBySearch($request);
  305.         return $this->render('@UVDeskSupportCenter/Knowledgebase/search.html.twig', [
  306.             'search'   => $searchQuery,
  307.             'articles' => $articleCollection,
  308.             'breadcrumbs' => [
  309.                 ['label' => $this->translator->trans('Support Center'), 'url' => $this->generateUrl('helpdesk_knowledgebase')],
  310.                 ['label' => $searchQuery'url' => '#'],
  311.             ],
  312.         ]);
  313.     }
  314. }