vendor/uvdesk/core-framework/Controller/Account.php line 58

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  6. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Recaptcha;
  7. use Symfony\Component\EventDispatcher\GenericEvent;
  8. use Webkul\UVDesk\CoreFrameworkBundle\Form\UserAccount;
  9. use Webkul\UVDesk\CoreFrameworkBundle\Form\UserProfile;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Webkul\UVDesk\CoreFrameworkBundle\Entity\UserInstance;
  12. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportRole;
  13. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportTeam;
  14. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportGroup;
  15. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportPrivilege;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  17. use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
  18. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  19. use Webkul\UVDesk\CoreFrameworkBundle\Services\UserService;
  20. use Webkul\UVDesk\CoreFrameworkBundle\Services\UVDeskService;
  21. use Webkul\UVDesk\CoreFrameworkBundle\Services\FileUploadService;
  22. use Webkul\UVDesk\CoreFrameworkBundle\FileSystem\FileSystem;
  23. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  24. use Symfony\Contracts\Translation\TranslatorInterface;
  25. use Symfony\Component\Filesystem\Filesystem as Fileservice;
  26. class Account extends AbstractController
  27. {
  28.     private $userService;
  29.     private $authenticationUtils;
  30.     private $eventDispatcher;
  31.     private $translator;
  32.     private $passwordEncoder;
  33.     private $uvdeskService;
  34.     private $fileSystem;
  35.     private $fileUploadService;
  36.     public function __construct(UserService $userServiceEventDispatcherInterface $eventDispatcherTranslatorInterface $translatorUserPasswordEncoderInterface $passwordEncoderUVDeskService $uvdeskServiceFileSystem $fileSystemFileUploadService $fileUploadService)
  37.     {
  38.         $this->userService $userService;
  39.         $this->eventDispatcher $eventDispatcher;
  40.         $this->translator $translator;
  41.         $this->passwordEncoder $passwordEncoder;
  42.         $this->uvdeskService $uvdeskService;
  43.         $this->fileSystem $fileSystem;
  44.         $this->fileUploadService $fileUploadService;
  45.         
  46.     }
  47.     
  48.     private function encodePassword(User $user$plainPassword)
  49.     {
  50.         $encodedPassword $this->passwordEncoder->encodePassword($user$plainPassword);
  51.     }
  52.     public function loadDashboard(Request $request)
  53.     {
  54.         return $this->render('@UVDeskCoreFramework//dashboard.html.twig', []);
  55.     }
  56.     public function listAgents(Request $request)
  57.     {
  58.         if (!$this->userService->isAccessAuthorized('ROLE_AGENT_MANAGE_AGENT')){          
  59.             return $this->redirect($this->generateUrl('helpdesk_member_dashboard'));
  60.         }
  61.         return $this->render('@UVDeskCoreFramework/Agents/listSupportAgents.html.twig');
  62.     }
  63.     
  64.     public function loadProfile(Request $request)
  65.     {
  66.         // @TODO: Refactor
  67.         $em $this->getDoctrine()->getManager();
  68.         $user $this->getUser();
  69.         $originalUser = clone $user;
  70.         $errors = [];
  71.         $dataFiles $request->files->get('user_form');
  72.         if ($request->getMethod() == "POST") {
  73.             $data     $request->request->all();
  74.             $dataFiles $request->files->get('user_form');
  75.             // Profile upload validation
  76.             $validMimeType = ['image/jpeg''image/png''image/jpg'];
  77.             if(isset($dataFiles['profileImage'])){
  78.                 if(!in_array($dataFiles['profileImage']->getMimeType(), $validMimeType)){
  79.                     $this->addFlash('warning'$this->translator->trans('Error ! Profile image is not valid, please upload a valid format'));
  80.                     return $this->redirect($this->generateUrl('helpdesk_member_profile'));
  81.                 }
  82.             }
  83.             $data $data['user_form'];
  84.             $checkUser $em->getRepository(User::class)->findOneBy(array('email' => $data['email']));
  85.             $errorFlag 0;
  86.             if ($checkUser) {
  87.                 if($checkUser->getId() != $user->getId())
  88.                     $errorFlag 1;
  89.             }
  90.             if (!$errorFlag) {
  91.                 $password $user->getPassword();
  92.                 $form $this->createForm(UserProfile::class, $user);
  93.                 $form->handleRequest($request);
  94.                 $form->submit($data);
  95.                 
  96.                 if ($form->isValid()) {
  97.                     if ($data != null) {
  98.                         $submittedPassword $data['password']['first'];
  99.                         $encoder $this->passwordEncoder;
  100.                         // save previous password if password is blank or null provided
  101.                         $encodedPassword = empty($submittedPassword) ? $password $encoder->encodePassword($user$submittedPassword);
  102.                         if (!empty($encodedPassword) ) {
  103.                             $user->setPassword($encodedPassword);
  104.                         } else {
  105.                             $this->addFlash('warning'$this->translator->trans('Error! Given current password is incorrect.'));
  106.                             return $this->redirect($this->generateUrl('helpdesk_member_profile'));
  107.                         }
  108.                     }
  109.                     $user->setFirstName($data['firstName']);
  110.                     $user->setLastName($data['lastName']);
  111.                     $user->setEmail($data['email']);
  112.                     $user->setTimezone($data['timezone']);
  113.                     $user->setTimeformat($data['timeformat']);
  114.                     $em->persist($user);
  115.                     $em->flush();
  116.                     $userInstance $em->getRepository(UserInstance::class)->findOneBy(array('user' => $user->getId()));
  117.                     $userInstance $this->userService->getUserDetailById($user->getId());
  118.                     if (isset($dataFiles['profileImage'])) {
  119.                         $previousImage $userInstance->getProfileImagePath();
  120.                         if($previousImage != null){
  121.                             $image str_replace("\\","/",$this->getParameter('kernel.project_dir').'/public'.$previousImage);
  122.                             $check $this->fileUploadService->fileRemoveFromFolder($image); 
  123.                         }
  124.                             $assetDetails $this->fileSystem->getUploadManager()->uploadFile($dataFiles['profileImage'], 'profile');
  125.                             $userInstance->setProfileImagePath($assetDetails['path']);
  126.                     }
  127.                     // Removed profile image from database and path
  128.                     $fileService = new Fileservice;
  129.                     if ($request->get('removeImage') == 'on') {
  130.                         if ($userInstance->getProfileImagePath()) {
  131.                             $fileService->remove($this->getParameter('kernel.project_dir').'/public'.$userInstance->getProfileImagePath());
  132.                         }
  133.                         
  134.                         $userInstance $userInstance->setProfileImagePath(null);
  135.                     }
  136.                     $userInstance  $userInstance->setContactNumber($data['contactNumber']);
  137.                     $userInstance  $userInstance->setSignature($data['signature']);
  138.                     $em->persist($userInstance);
  139.                     $em->flush();
  140.                     $roleId $user->getAgentInstance()->getSupportRole()->getId();
  141.                     
  142.                     if(in_array($roleId,  [1,2])) {
  143.                         // Recaptcha Setting
  144.                         $recaptchaSetting $em->getRepository(Recaptcha::class)->findOneBy(['id' => 1]);
  145.                         if($recaptchaSetting) {
  146.                             $recaptchaSetting->setSiteKey($data['recaptcha_site_key']);
  147.                             $recaptchaSetting->setSecretKey($data['recaptcha_secret_key']);
  148.                             if(isset($data['recaptcha_status'])) {
  149.                                 $recaptchaSetting->setIsActive(true);
  150.                             } else {
  151.                                 $recaptchaSetting->setIsActive(false);
  152.                             }
  153.                             $em->persist($recaptchaSetting);
  154.                             $em->flush();
  155.                         } else {
  156.                             $recaptchaNew = new Recaptcha;
  157.                             $recaptchaNew->setSiteKey($data['recaptcha_site_key']);
  158.                             $recaptchaNew->setSecretKey($data['recaptcha_secret_key']);
  159.                             if(isset($data['recaptcha_status'])) {
  160.                                 $recaptchaNew->setIsActive(true);
  161.                             } else {
  162.                                 $recaptchaNew->setIsActive(false);
  163.                             }
  164.                             $em->persist($recaptchaNew);
  165.                             $em->flush();
  166.                         }
  167.                     }
  168.                     $this->addFlash('success'$this->translator->trans('Success ! Profile update successfully.'));
  169.                     return $this->redirect($this->generateUrl('helpdesk_member_profile'));
  170.                 } else {
  171.                     $errors $form->getErrors();
  172.                     dump($errors);
  173.                     die;
  174.                     $errors $this->getFormErrors($form);
  175.                 }
  176.             } else {
  177.                 $this->addFlash('warning'$this->translator->trans('Error ! User with same email is already exist.'));
  178.                 return $this->redirect($this->generateUrl('helpdesk_member_profile'));
  179.             }
  180.         }
  181.         return $this->render('@UVDeskCoreFramework//profile.html.twig', array(
  182.             'user' => $user,
  183.             'errors' => json_encode($errors)
  184.         ));
  185.     }
  186.     public function editAgent($agentId)
  187.     {
  188.         if (!$this->userService->isAccessAuthorized('ROLE_AGENT_MANAGE_AGENT')) {
  189.             return $this->redirect($this->generateUrl('helpdesk_member_dashboard'));
  190.         }
  191.             // @TODO: Refactor
  192.         $em $this->getDoctrine()->getManager();
  193.         $request $this->container->get('request_stack')->getCurrentRequest();
  194.         $activeUser $this->userService->getSessionUser();
  195.         $user $em->getRepository(User::class)->find($agentId);
  196.         $instanceRole $user->getAgentInstance()->getSupportRole()->getCode();
  197.         if (empty($user)) {
  198.             dump('Not found');die;
  199.         }
  200.         switch (strtoupper($request->getMethod())) {
  201.             case 'POST':
  202.                 $formErrors = [];
  203.                 $data      $request->request->get('user_form');
  204.                 $dataFiles $request->files->get('user_form');
  205.                 // Agent Profile upload validation
  206.                 $validMimeType = ['image/jpeg''image/png''image/jpg'];
  207.                 if(isset($dataFiles['profileImage'])){
  208.                     if(!in_array($dataFiles['profileImage']->getMimeType(), $validMimeType)){
  209.                         $this->addFlash('warning'$this->translator->trans('Error ! Profile image is not valid, please upload a valid format'));
  210.                         $response $this->render('@UVDeskCoreFramework/Agents/updateSupportAgent.html.twig', [
  211.                             'user'         => $user,
  212.                             'instanceRole' => $instanceRole,
  213.                             'errors'       => json_encode([])
  214.                         ]);
  215.                         break;
  216.                     }
  217.                 }
  218.                 $checkUser $em->getRepository(User::class)->findOneBy(array('email'=> $data['email']));
  219.                 $errorFlag 0;
  220.                 if ($checkUser && $checkUser->getId() != $agentId) {
  221.                     $errorFlag 1;
  222.                 }
  223.                 if (!$errorFlag) {
  224.                     if (
  225.                         isset($data['password']['first']) && !empty(trim($data['password']['first'])) 
  226.                         && isset($data['password']['second'])  && !empty(trim($data['password']['second'])) 
  227.                         && trim($data['password']['first']) == trim($data['password']['second'])) {
  228.                         $encodedPassword $this->passwordEncoder->encodePassword($user$data['password']['first']);
  229.                         $user->setPassword($encodedPassword);
  230.                     }
  231.                     $user->setFirstName($data['firstName']);
  232.                     $user->setLastName($data['lastName']);
  233.                     $user->setEmail($data['email']);
  234.                     $user->setIsEnabled(true);
  235.                     
  236.                     $userInstance $em->getRepository(UserInstance::class)->findOneBy(array('user' => $agentId'supportRole' => array(123)));
  237.                     
  238.                     $oldSupportTeam = ($supportTeamList $userInstance != null $userInstance->getSupportTeams() : null) ? $supportTeamList->toArray() : [];
  239.                     $oldSupportGroup  = ($supportGroupList $userInstance != null $userInstance->getSupportGroups() : null) ? $supportGroupList->toArray() : [];
  240.                     $oldSupportedPrivilege = ($supportPrivilegeList $userInstance != null $userInstance->getSupportPrivileges() : null)? $supportPrivilegeList->toArray() : [];
  241.                     if(isset($data['role'])) {
  242.                         $role $em->getRepository(SupportRole::class)->findOneBy(array('code' => $data['role']));
  243.                         $userInstance->setSupportRole($role);
  244.                     }
  245.                     if (isset($data['ticketView'])) {
  246.                         $userInstance->setTicketAccessLevel($data['ticketView']);
  247.                     }
  248.                     $userInstance->setDesignation($data['designation']);
  249.                     $userInstance->setContactNumber($data['contactNumber']);
  250.                     $userInstance->setSource('website');
  251.                     
  252.                     if (isset($dataFiles['profileImage'])) {
  253.                         // Removed profile image from database and path
  254.                         $fileService = new Fileservice;
  255.                         if ($userInstance->getProfileImagePath()) {
  256.                             $fileService->remove($this->getParameter('kernel.project_dir').'/public'.$userInstance->getProfileImagePath());
  257.                         }
  258.                         
  259.                         $assetDetails $this->fileSystem->getUploadManager()->uploadFile($dataFiles['profileImage'], 'profile');
  260.                         $userInstance->setProfileImagePath($assetDetails['path']);
  261.                     }
  262.                     $userInstance->setSignature($data['signature']);
  263.                     $userInstance->setIsActive(isset($data['isActive']) ? $data['isActive'] : 0);
  264.                     if(isset($data['userSubGroup'])){
  265.                         foreach ($data['userSubGroup'] as $userSubGroup) {
  266.                             if($userSubGrp $this->uvdeskService->getEntityManagerResult(
  267.                                 SupportTeam::class,
  268.                                 'findOneBy', [
  269.                                     'id' => $userSubGroup
  270.                                 ]
  271.                             )
  272.                             )
  273.                                 if(!$oldSupportTeam || !in_array($userSubGrp$oldSupportTeam)){
  274.                                     $userInstance->addSupportTeam($userSubGrp);
  275.                                 }elseif($oldSupportTeam && ($key array_search($userSubGrp$oldSupportTeam)) !== false)
  276.                                     unset($oldSupportTeam[$key]);
  277.                         }
  278.                         foreach ($oldSupportTeam as $removeteam) {
  279.                             $userInstance->removeSupportTeam($removeteam);
  280.                             $em->persist($userInstance);
  281.                         }
  282.                     }
  283.                     if(isset($data['groups'])){
  284.                         foreach ($data['groups'] as $userGroup) {
  285.                             if($userGrp $this->uvdeskService->getEntityManagerResult(
  286.                                 SupportGroup::class,
  287.                                 'findOneBy', [
  288.                                     'id' => $userGroup
  289.                                 ]
  290.                             )
  291.                             )
  292.                                 if(!$oldSupportGroup || !in_array($userGrp$oldSupportGroup)){
  293.                                     $userInstance->addSupportGroup($userGrp);
  294.                                 }elseif($oldSupportGroup && ($key array_search($userGrp$oldSupportGroup)) !== false)
  295.                                     unset($oldSupportGroup[$key]);
  296.                         }
  297.                         foreach ($oldSupportGroup as $removeGroup) {
  298.                             $userInstance->removeSupportGroup($removeGroup);
  299.                             $em->persist($userInstance);
  300.                         }
  301.                     }
  302.                     if(isset($data['agentPrivilege'])){
  303.                         foreach ($data['agentPrivilege'] as $supportPrivilege) {
  304.                             if($supportPlg $this->uvdeskService->getEntityManagerResult(
  305.                                 SupportPrivilege::class,
  306.                                 'findOneBy', [
  307.                                     'id' => $supportPrivilege
  308.                                 ]
  309.                             )
  310.                             )
  311.                                 if(!$oldSupportedPrivilege || !in_array($supportPlg$oldSupportedPrivilege)){
  312.                                     $userInstance->addSupportPrivilege($supportPlg);
  313.                                 }elseif($oldSupportedPrivilege && ($key array_search($supportPlg$oldSupportedPrivilege)) !== false)
  314.                                     unset($oldSupportedPrivilege[$key]);
  315.                         }
  316.                         foreach ($oldSupportedPrivilege as $removeGroup) {
  317.                             $userInstance->removeSupportPrivilege($removeGroup);
  318.                             $em->persist($userInstance);
  319.                         }
  320.                     }
  321.                     $userInstance->setUser($user);
  322.                     $user->addUserInstance($userInstance);
  323.                     $em->persist($user);
  324.                     $em->persist($userInstance);
  325.                     $em->flush();
  326.                     // Trigger customer Update event
  327.                     $event = new GenericEvent(CoreWorkflowEvents\Agent\Update::getId(), [
  328.                         'entity' => $user,
  329.                     ]);
  330.                     $this->eventDispatcher->dispatch($event'uvdesk.automation.workflow.execute');
  331.                     $this->addFlash('success'$this->translator->trans('Success ! Agent updated successfully.'));
  332.                     return $this->redirect($this->generateUrl('helpdesk_member_account_collection'));
  333.                 } else {
  334.                     $this->addFlash('warning'$this->translator->trans('Error ! User with same email is already exist.'));
  335.                 }
  336.                 $response $this->render('@UVDeskCoreFramework/Agents/updateSupportAgent.html.twig', [
  337.                     'user' => $user,
  338.                     'instanceRole' => $instanceRole,
  339.                     'errors' => json_encode([])
  340.                 ]);
  341.                 break;
  342.             default:
  343.                 $response $this->render('@UVDeskCoreFramework/Agents/updateSupportAgent.html.twig', [
  344.                     'user'         => $user,
  345.                     'instanceRole' => $instanceRole,
  346.                     'errors'       => json_encode([])
  347.                 ]);
  348.                 break;
  349.         }
  350.         return $response;
  351.     }
  352.     public function createAgent(Request $request)
  353.     {
  354.         // @TODO: Refactor
  355.         if(!$this->userService->isAccessAuthorized('ROLE_AGENT_MANAGE_AGENT')){          
  356.             return $this->redirect($this->generateUrl('helpdesk_member_dashboard'));
  357.         }
  358.         $user = new User();
  359.         $userServiceContainer $this->userService;
  360.         if ('POST' == $request->getMethod()) {
  361.             $formDetails $request->request->get('user_form');
  362.             $uploadedFiles $request->files->get('user_form');
  363.             $entityManager $this->getDoctrine()->getManager();
  364.             // Profile upload validation
  365.             $validMimeType = ['image/jpeg''image/png''image/jpg'];
  366.             if(isset($uploadedFiles['profileImage'])){
  367.                 if(!in_array($uploadedFiles['profileImage']->getMimeType(), $validMimeType)){
  368.                     $this->addFlash('warning'$this->translator->trans('Error ! Profile image is not valid, please upload a valid format'));
  369.                     return $this->redirect($this->generateUrl('helpdesk_member_create_account'));
  370.                 }
  371.             }
  372.             $user $entityManager->getRepository(User::class)->findOneByEmail($formDetails['email']);
  373.             $agentInstance = !empty($user) ? $user->getAgentInstance() : null;
  374.             if (empty($agentInstance)) {
  375.                 if (!empty($formDetails)) {
  376.                     $fullname trim(implode(' ', [$formDetails['firstName'], $formDetails['lastName']]));
  377.                     $supportRole $entityManager->getRepository(SupportRole::class)->findOneByCode($formDetails['role']);
  378.                     $user $this->userService->createUserInstance($formDetails['email'], $fullname$supportRole, [
  379.                         'contact' => $formDetails['contactNumber'],
  380.                         'source' => 'website',
  381.                         'active' => !empty($formDetails['isActive']) ? true false,
  382.                         'image' => $uploadedFiles['profileImage'],
  383.                         'signature' => $formDetails['signature'],
  384.                         'designation' => $formDetails['designation'],
  385.                     ]);
  386.                     if(!empty($user)){
  387.                         $user->setIsEnabled(true);
  388.                         $entityManager->persist($user);
  389.                         $entityManager->flush();
  390.                     }
  391.                     $userInstance $user->getAgentInstance();
  392.                     if (isset($formDetails['ticketView'])) {
  393.                         $userInstance->setTicketAccessLevel($formDetails['ticketView']);
  394.                     }
  395.                     // Map support team
  396.                     if (!empty($formDetails['userSubGroup'])) {
  397.                         $supportTeamRepository $entityManager->getRepository(SupportTeam::class);
  398.                         foreach ($formDetails['userSubGroup'] as $supportTeamId) {
  399.                             $supportTeam $supportTeamRepository->findOneById($supportTeamId);
  400.                             if (!empty($supportTeam)) {
  401.                                 $userInstance->addSupportTeam($supportTeam);
  402.                             }
  403.                         }
  404.                     }
  405.                     // Map support group
  406.                     if (!empty($formDetails['groups'])) {
  407.                         $supportGroupRepository $entityManager->getRepository(SupportGroup::class);
  408.                         foreach ($formDetails['groups'] as $supportGroupId) {
  409.                             $supportGroup $supportGroupRepository->findOneById($supportGroupId);
  410.                             if (!empty($supportGroup)) {
  411.                                 $userInstance->addSupportGroup($supportGroup);
  412.                             }
  413.                         }
  414.                     }
  415.                     // Map support privileges
  416.                     if (!empty($formDetails['agentPrivilege'])) {
  417.                         $supportPrivilegeRepository $entityManager->getRepository(SupportPrivilege::class);
  418.                         foreach($formDetails['agentPrivilege'] as $supportPrivilegeId) {
  419.                             $supportPrivilege $supportPrivilegeRepository->findOneById($supportPrivilegeId);
  420.                             if (!empty($supportPrivilege)) {
  421.                                 $userInstance->addSupportPrivilege($supportPrivilege);
  422.                             }
  423.                         }
  424.                     }
  425.                     $entityManager->persist($userInstance);
  426.                     $entityManager->flush();
  427.                     $this->addFlash('success'$this->translator->trans('Success ! Agent added successfully.'));
  428.                     return $this->redirect($this->generateUrl('helpdesk_member_account_collection'));
  429.                 }
  430.             } else {
  431.                 $this->addFlash('warning'$this->translator->trans('Error ! User with same email already exist.'));
  432.             }
  433.         }
  434.         return $this->render('@UVDeskCoreFramework/Agents/createSupportAgent.html.twig', [
  435.             'user' => $user,
  436.             'errors' => json_encode([])
  437.         ]);
  438.     }
  439. }