vendor\uvdesk\core-framework\Services\UserService.php line 72

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Services;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\Common\Collections\Criteria;
  5. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportRole;
  9. use Webkul\UVDesk\CoreFrameworkBundle\Entity\UserInstance;
  10. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Ticket;
  11. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportPrivilege;
  12. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportGroup;    
  13. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportTeam;
  14. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SavedReplies;
  15. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Website;
  16. use Symfony\Component\HttpFoundation\RequestStack;
  17. use Symfony\Component\EventDispatcher\GenericEvent;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Webkul\UVDesk\CoreFrameworkBundle\Workflow\Events as CoreWorkflowEvents;
  20. use Symfony\Component\Translation\Translator;
  21. use Symfony\Component\Translation\Loader\YamlFileLoader;
  22. use Twig\Environment as TwigEnvironment;
  23. use Symfony\Component\Filesystem\Filesystem as Fileservice;
  24. use Webkul\UVDesk\SupportCenterBundle\Entity\KnowledgebaseWebsite;
  25. class UserService
  26. {
  27.     protected $container;
  28.     protected $requestStack;
  29.     protected $entityManager;
  30.     protected $twig;
  31.     public function __construct(ContainerInterface $containerRequestStack $requestStackEntityManagerInterface $entityManagerTwigEnvironment $twig)
  32.     {
  33.         $this->container $container;
  34.         $this->requestStack $requestStack;
  35.         $this->entityManager $entityManager;
  36.         $this->twig $twig;
  37.     }
  38.     public function getCustomFieldTemplateCustomer()
  39.     {
  40.         $request $this->requestStack->getCurrentRequest();
  41.         //get the ticket
  42.         $ticket $this->entityManager->getRepository(Ticket::class)->findOneById($request->attributes->get('id'));
  43.         $getCustomerCustomFieldSnippet $this->container->get('custom.field.service')->getCustomerCustomFieldSnippet($ticket);
  44.         if (sizeof($getCustomerCustomFieldSnippet["customFieldCollection"]) > ) {
  45.             return $this->twig->render('@_uvdesk_extension_uvdesk_form_component/widgets/CustomFields/customFieldSnippetCustomer.html.twig'
  46.                 $getCustomerCustomFieldSnippet);
  47.         }
  48.         return ;
  49.     }
  50.     public function isGranted($role) {
  51.         $securityContext $this->container->get('security.token_storage');
  52.        
  53.         try {
  54.             return (bool) ($role == $securityContext->getToken()->getRoles()[0]->getRole());
  55.         } catch (AuthenticationCredentialsNotFoundException $e) {
  56.             // @TODO: Handle Authentication Failure
  57.         }
  58.         return false;
  59.     }
  60.     
  61.     public function getSessionUser()
  62.     {
  63.         $user $this->container->get('security.token_storage')->getToken()->getUser();
  64.         return $user instanceof User $user null;
  65.     }
  66.     public function getCurrentUser()
  67.     {
  68.         if ($this->container->get('security.token_storage')->getToken()) {
  69.             return $this->container->get('security.token_storage')->getToken()->getUser();
  70.         } else {
  71.             return false;
  72.         }
  73.     }
  74.     
  75.     public function isAccessAuthorized($scopeUser $user null)
  76.     {
  77.         // Return false if no user is provided
  78.         if (empty($user) && !($user $this->getSessionUser())) {
  79.             return false;
  80.         }
  81.         try {
  82.             $userRole $user->getCurrentInstance()->getSupportRole()->getCode();
  83.         } catch (\Exception $error) {
  84.             $userRole '';
  85.         }
  86.         switch ($userRole) {
  87.             case 'ROLE_SUPER_ADMIN':
  88.             case 'ROLE_ADMIN':
  89.                 return true;
  90.             case 'ROLE_AGENT':
  91.                 $agentPrivileges $this->getUserPrivileges($this->getCurrentUser()->getId());
  92.                 $agentPrivileges array_merge($agentPrivileges, ['saved_filters_action''saved_replies']);
  93.                 
  94.                 return in_array($scope$agentPrivileges) ? true false;
  95.             case 'ROLE_CUSTOMER':
  96.             default:
  97.                 break;
  98.         }
  99.         return true;
  100.     }
  101.     public function getUserPrivileges($userId)
  102.     {
  103.         static $agentPrivilege = [];
  104.         
  105.         if (isset($agentPrivilege[$userId])) {
  106.             return $agentPrivilege[$userId];
  107.         }
  108.         
  109.         $userPrivileges = array();
  110.         $user $this->entityManager->getRepository(User::class)->find($userId);
  111.         $privileges $user->getAgentInstance()->getSupportPrivileges();  
  112.       
  113.         if ($privileges) {
  114.             foreach ($privileges as $privilege) {
  115.                 $userPrivileges array_merge($userPrivileges$privilege->getPrivileges());
  116.             }
  117.         }
  118.         
  119.         $agentPrivilege[$userId] = $this->agentPrivilege[$userId] = $userPrivileges;  
  120.         return $userPrivileges;
  121.     }
  122.     public function getSupportPrivileges()
  123.     {
  124.         $qb $this->entityManager->createQueryBuilder();
  125.         $qb->select("supportPrivilege")->from(SupportPrivilege::class, 'supportPrivilege');
  126.         
  127.         return $qb->getQuery()->getArrayResult();
  128.     }
  129.     public function getSupportGroups(Request $request null)
  130.     {
  131.         static $results;
  132.         if(null !== $results)
  133.             return $results;
  134.         $qb $this->entityManager->createQueryBuilder();
  135.         $qb->select('supportGroup.id, supportGroup.name')->from(SupportGroup::class, 'supportGroup')
  136.                 ->andwhere('supportGroup.isActive = 1');
  137.         if($request) {
  138.             $qb->andwhere("supportGroup.name LIKE :groupName");
  139.             $qb->setParameter('groupName''%'.urldecode($request->query->get('query')).'%');
  140.             $qb->andwhere("supportGroup.id NOT IN (:ids)");
  141.             $qb->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  142.         }
  143.         return $results $qb->getQuery()->getArrayResult();
  144.     }
  145.     public function getSupportTeams(Request $request null)
  146.     {
  147.         static $results;
  148.         if(null !== $results)
  149.             return $results;
  150.         $queryBuilder $this->entityManager->createQueryBuilder()
  151.             ->select("user.id, user.email, CONCAT(user.firstName, ' ', user.lastName) as name, userInstance.profileImagePath as smallThumbnail")
  152.             ->from(User::class, 'user')
  153.             ->leftJoin('user.userInstance''userInstance')
  154.             ->leftJoin('userInstance.supportRole''supportRole')
  155.             ->where('supportRole.code != :customerRole')->setParameter('customerRole''ROLE_CUSTOMER')
  156.             ->andWhere('userInstance.isActive = :isUserActive')->setParameter('isUserActive'true)
  157.             ->orderBy('name'Criteria::ASC);
  158.         if ($request && null != $request->query->get('query')) {
  159.             $queryBuilder
  160.                 ->andWhere("CONCAT(dt.firstName,' ', dt.lastName) LIKE :customerName")
  161.                 ->setParameter('customerName''%'.urldecode($request->query->get('query')).'%');
  162.         }
  163.         $qb $this->entityManager->createQueryBuilder();
  164.         $qb->select('supportTeam.id, supportTeam.name')
  165.            ->from(SupportTeam::class, 'supportTeam');
  166.         $qb->andwhere('supportTeam.isActive = 1');
  167.         
  168.         if($request) {
  169.             $qb->andwhere("supportTeam.name LIKE :subGroupName");
  170.             $qb->setParameter('subGroupName''%'.urldecode($request->query->get('query')).'%');
  171.             $qb->andwhere("supportTeam.id NOT IN (:ids)");
  172.             $qb->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  173.         }
  174.         return $results $qb->getQuery()->getResult();
  175.     }
  176.     public function createUserInstance($email$nameSupportRole $role, array $extras = [])
  177.     {
  178.         $user $this->entityManager->getRepository(User::class)->findOneByEmail($email) ?: new User();
  179.         
  180.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'knowledgebase']);
  181.         $timeZone $website->getTimezone();
  182.         $timeFormat $website->getTimeformat();
  183.         if (null == $user->getId()) {
  184.             $name explode(' 'trim($name));
  185.             
  186.             $user->setEmail($email);
  187.             $user->setFirstName(isset($extras['firstName']) ? $extras['firstName'] : array_shift($name));
  188.             $user->setLastName(trim(implode(' '$name)));
  189.             $user->setIsEnabled($extras['active']);
  190.             $user->setTimeZone($timeZone);
  191.             $user->setTimeFormat($timeFormat);
  192.             $this->entityManager->persist($user);
  193.             $this->entityManager->flush();
  194.         }
  195.         
  196.         $userInstance 'ROLE_CUSTOMER' == $role->getCode() ? $user->getCustomerInstance() : $user->getAgentInstance();
  197.         
  198.         if (empty($userInstance)) {
  199.             $userInstance = new UserInstance();
  200.                 
  201.             $userInstance->setUser($user);
  202.             $userInstance->setSupportRole($role);
  203.             $userInstance->setContactNumber(!empty($extras['contact']) ? $extras['contact'] : null);
  204.             $userInstance->setSkypeId(!empty($extras['skype']) ? $extras['skype'] : null);
  205.             $userInstance->setDesignation(!empty($extras['designation']) ? $extras['designation'] : null);
  206.             $userInstance->setSignature(!empty($extras['signature']) ? $extras['signature'] : null);
  207.             $userInstance->setSource(!empty($extras['source']) ? $extras['source'] : 'website');
  208.             $userInstance->setIsActive(!empty($extras['active']) ? (bool) $extras['active'] : false);
  209.             $userInstance->setIsVerified(!empty($extras['verified']) ? (bool) $extras['verified'] : false);
  210.             $userInstance->setIsStarred(!empty($extras['starred']) ? (bool) $extras['starred'] : false);
  211.             if (!empty($extras['image'])) {
  212.                 $assetDetails $this->container->get('uvdesk.core.file_system.service')->getUploadManager()->uploadFile($extras['image'], 'profile');
  213.                 if (!empty($assetDetails)) {
  214.                     $userInstance->setProfileImagePath($assetDetails['path']);
  215.                 }
  216.             }
  217.             $this->entityManager->persist($userInstance);
  218.             $this->entityManager->flush();
  219.             $user->addUserInstance($userInstance);
  220.             // Trigger user created event
  221.             $eventId 'ROLE_CUSTOMER' == $role->getCode() ? CoreWorkflowEvents\Customer\Create::getId() : CoreWorkflowEvents\Agent\Create::getId();
  222.             $event = new GenericEvent($eventId, ['entity' => $user]);
  223.             $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  224.         }
  225.         return $user;
  226.     }
  227.     public function getAgentPartialDataCollection(Request $request null)
  228.     {
  229.         $queryBuilder $this->entityManager->createQueryBuilder()
  230.             ->select("user.id, user.email, CONCAT(user.firstName, ' ', COALESCE(user.lastName, '')) as name, userInstance.profileImagePath as smallThumbnail")
  231.             ->from(User::class, 'user')
  232.             ->leftJoin('user.userInstance''userInstance')
  233.             ->leftJoin('userInstance.supportRole''supportRole')
  234.             ->where('supportRole.code != :customerRole')->setParameter('customerRole''ROLE_CUSTOMER')
  235.             ->andWhere('userInstance.isActive = :isUserActive')->setParameter('isUserActive'true)
  236.             ->orderBy('name'Criteria::ASC);
  237.         if ($request && null != $request->query->get('query')) {
  238.             $queryBuilder
  239.                 ->andWhere("CONCAT(user.firstName,' ', user.lastName) LIKE :customerName")
  240.                 ->setParameter('customerName''%'.urldecode($request->query->get('query')).'%');
  241.         }
  242.         if ($request && null != $request->query->get('not')) {
  243.             $queryBuilder
  244.                 ->andwhere("u.id NOT IN (:ids)")
  245.                 ->setParameter('ids'explode(','urldecode($request->query->get('not'))));
  246.         }
  247.         return $queryBuilder->getQuery()->getArrayResult();
  248.     }
  249.     public function getAgentsPartialDetails(Request $request null) {
  250.         static $agents;
  251.         if (null !== $agents)
  252.             return $agents;
  253.         $qb $this->entityManager->createQueryBuilder();
  254.         $qb->select("u.id, userInstance.id as udId,u.email,CONCAT(u.firstName,' ', u.lastName) AS name,userInstance.profileImagePath as smallThumbnail")->from(User::class, 'u')
  255.                 ->leftJoin('u.userInstance''userInstance')
  256.                 ->andwhere('userInstance.supportRole != :roles')
  257.                 ->setParameter('roles'4)
  258.                 ->andwhere('userInstance.isActive = 1')
  259.                 ->orderBy('name','ASC');
  260.         if($request) {
  261.             $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName");
  262.             $qb->setParameter('customerName''%'.urldecode($request->query->get('query')).'%');
  263.             $qb->andwhere("u.id NOT IN (:ids)");
  264.             $qb->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  265.         }
  266.         $data $agents $qb->getQuery()->getArrayResult();
  267.         return $data;
  268.     }
  269.     public function getAgentDetailById($agentId) {
  270.         if(!$agentId) return;
  271.         $qb $this->entityManager->createQueryBuilder();
  272.         $qb->select("DISTINCT u.id,u.email,CONCAT(u.firstName,' ', COALESCE(u.lastName,'')) AS name,u.firstName,u.lastName,u.isEnabled,userInstance.profileImagePath,userInstance.profileImagePath as smallThumbnail,userInstance.isActive, userInstance.isVerified, userInstance.designation, userInstance.contactNumber,userInstance.signature,userInstance.ticketAccessLevel")
  273.             ->from(User::class, 'u')
  274.             ->leftJoin('u.userInstance''userInstance')
  275.             ->andwhere('userInstance.supportRole != :roles')
  276.             ->andwhere('u.id = :agentId')
  277.             ->setParameter('roles'4)
  278.             ->setParameter('agentId'$agentId);
  279.         $result $qb->getQuery()->getResult();
  280.         return isset($result[0]) ? $result[0] : null;
  281.     }
  282.     public function getUsersByGroupId($groupId)
  283.     {
  284.         $qb $this->entityManager->createQueryBuilder();
  285.         $qb->select("DISTINCT user.id, user.email, CONCAT(user.firstName, ' ', user.lastName) AS name, userInstance.profileImagePath as smallThumbnail")
  286.             ->from(User::class, 'user')
  287.             ->leftJoin('user.userInstance''userInstance')
  288.                 ->leftJoin('userInstance.supportGroups''supportGroup')
  289.                 ->andWhere('userInstance.supportRole != :roles')->setParameter('roles'4)
  290.                 ->andwhere('supportGroup.id = :groupId')->setParameter('groupId'$groupId)
  291.                 ->andwhere('userInstance.isActive = 1');
  292.         $data $qb->getQuery()->getArrayResult();
  293.         return $data;
  294.     }
  295.     public function getUsersBySubGroupId($subGroupId)
  296.     {
  297.         $qb $this->entityManager->createQueryBuilder();
  298.         $qb->select("DISTINCT user.id, supportTeam.id as udId,user.email,CONCAT(user.firstName,' ', user.lastName) AS name,userInstance.profileImagePath as smallThumbnail")
  299.                 ->from(User::class, 'user')
  300.                 ->leftJoin('user.userInstance''userInstance')
  301.                 ->leftJoin('userInstance.supportTeams''supportTeam')
  302.                 ->andwhere('userInstance.supportRole != :roles')
  303.                 ->andwhere('supportTeam.id = :subGroupId')
  304.                 ->setParameter('roles'4)
  305.                 ->setParameter('subGroupId'$subGroupId)
  306.                 ->andwhere('supportTeam.isActive = 1')
  307.                 ->andwhere('userInstance.isActive = 1');
  308.         $data $qb->getQuery()->getArrayResult();
  309.         return $data;
  310.     }
  311.     public function getCustomerDetailsById($customerId)
  312.     {
  313.         $qb $this->entityManager->createQueryBuilder();
  314.         $qb->select("user.id,user.email,CONCAT(user.firstName,' ', COALESCE(user.lastName,'')) AS name,user.firstName,user.lastName,user.isEnabled,userInstance.contactNumber,userInstance.profileImagePath,userInstance.profileImagePath as smallThumbnail,userInstance.isActive, userInstance.isVerified")->from(User::class, 'user')
  315.                 ->leftJoin('user.userInstance''userInstance')
  316.                 ->andwhere('userInstance.supportRole = :roles')
  317.                 ->andwhere('user.id = :customerId')
  318.                 ->setParameter('roles'4)
  319.                 ->setParameter('customerId'$customerId);
  320.         $result $qb->getQuery()->getResult();
  321.         return ($result $result[0] : null);
  322.     }
  323.     public function getCustomerPartialDetailById($customerId)
  324.     {
  325.         $qb $this->entityManager->createQueryBuilder();
  326.         $qb->select("u.id,u.email,CONCAT(u.firstName,' ', COALESCE(u.lastName,'')) AS name,u.firstName,u.lastName,userInstance.contactNumber,userInstance.profileImagePath,userInstance.profileImagePath as smallThumbnail")->from(User::class, 'u')
  327.             ->leftJoin('u.userInstance''userInstance')
  328.             ->andwhere('userInstance.supportRole = :roles')
  329.             ->andwhere('u.id = :customerId')
  330.             ->setParameter('roles'4)
  331.             ->setParameter('customerId'$customerId);
  332.         $result $qb->getQuery()->getResult();
  333.         return $result $result[0] : null;
  334.     }
  335.     public function getCustomersPartial(Request $request null)
  336.     {
  337.         $qb $this->entityManager->createQueryBuilder();
  338.         $qb->from(User::class, 'u');
  339.         $qb->select("DISTINCT u.id,CONCAT(u.firstName,' ', COALESCE(u.lastName,'')) AS name, userInstance.profileImagePath as smallThumbnail ")
  340.             ->leftJoin('u.userInstance''userInstance')
  341.             ->andwhere('userInstance.supportRole = :roles')
  342.             ->setParameter('roles'4)
  343.             ->orderBy('name','ASC');
  344.         
  345.         if ($request) {
  346.             if ($request->query->get('query')) {
  347.                 $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName OR u.email LIKE :customerName");
  348.             } else {
  349.                 $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName");
  350.             }
  351.             
  352.             $qb->setParameter('customerName''%'.urldecode($request->query->get('query')).'%')
  353.                 ->andwhere("u.id NOT IN (:ids)")
  354.                 ->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  355.         }
  356.         $query $qb->getQuery();
  357.         // $query->useResultCache(true, 3600, 'customer_list_'.$this->getCompany()->getId());
  358.         return $query->getScalarResult();
  359.     }
  360.     public function getCustomersCount()
  361.     {
  362.         $qb $this->entityManager->createQueryBuilder();
  363.         $qb->select($qb->expr()->countDistinct('c.id')."as customerCount")->from(Ticket::class, 't')
  364.                 ->leftJoin('t.customer''c');
  365.         $this->entityManager->getRepository(Ticket::class)->addPermissionFilter($qb$this->containerfalse);
  366.         return $qb->getQuery()->getSingleScalarResult();
  367.     }
  368.     public function getUserSubGroupIds($userId) {
  369.         $qb $this->entityManager->createQueryBuilder();
  370.         $qb->select('supportTeams.id')->from(User::class, 'user')
  371.                 ->leftJoin('user.userInstance','userInstance')
  372.                 ->leftJoin('userInstance.supportTeams','supportTeams')
  373.                 ->andwhere('user.id = :userId')
  374.                 ->andwhere('userInstance.supportRole != :agentRole')
  375.                 ->andwhere('supportTeams.isActive = 1')
  376.                 ->setParameter('userId'$userId)
  377.                 ->setParameter('agentRole''4'); 
  378.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  379.     }
  380.     public function getUserGroupIds($userId) {
  381.         $qb $this->entityManager->createQueryBuilder();
  382.         $qb->select('supportGroup.id')->from(User::class, 'user')
  383.                 ->leftJoin('user.userInstance','userInstance')
  384.                 ->leftJoin('userInstance.supportGroups','supportGroup')
  385.                 ->andwhere('user.id = :userId')
  386.                 ->andwhere('supportGroup.isActive = 1')
  387.                 ->setParameter('userId'$userId);
  388.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  389.     }
  390.     public function createUser($data)
  391.     {
  392.         $user = new User();
  393.         $user->setEmail($data['from']);
  394.         $user->setFirstName($data['firstName']);
  395.         $user->setLastName($data['lastName']);
  396.         $user->setIsEnabled($data['isActive']);
  397.         $this->entityManager->persist($user);
  398.         // $this->entityManager->flush();
  399.         $role $this->entityManager->getRepository(SupportRole::class)->find($data['role']);
  400.     
  401.         $userInstance = new UserInstance();
  402.         $userInstance->setSupportRole($role);
  403.         $userInstance->setUser($user);
  404.         $userInstance->setIsActive($data['isActive']);
  405.         $userInstance->setIsVerified(0);
  406.         if(isset($data['source']))
  407.             $userInstance->setSource($data['source']);
  408.         else
  409.             $userInstance->setSource('website');
  410.         if(isset($data['contactNumber'])) {
  411.             $userInstance->setContactNumber($data['contactNumber']);
  412.         }
  413.         if(isset($data['profileImage']) && $data['profileImage']) {
  414.                 $userInstance->setProfileImagePath($data['profileImage']);
  415.         }
  416.         $this->entityManager->persist($userInstance);
  417.         $this->entityManager->flush();
  418.         $user->addUserInstance($userInstance);
  419.         $this->entityManager->persist($user);
  420.         $this->entityManager->flush();
  421.         //$user->setUserName($userInstance->getName());
  422.         return $user;
  423.     }
  424.     public function getWebsiteConfiguration($code)
  425.     {
  426.         $enabled_bundles $this->container->getParameter('kernel.bundles');
  427.         
  428.         if (!in_array('UVDeskSupportCenterBundle'array_keys($enabled_bundles))) {
  429.             return [
  430.                 'id' =>  1,
  431.                 'website' =>  1,
  432.                 'status' =>  1,
  433.                 'brandColor' => '#7E91F0',
  434.                 'pageBackgroundColor' => '#FFFFFF',
  435.                 'headerBackgroundColor' => '#FFFFFF',
  436.                 'bannerBackgroundColor' => '#7085F4',
  437.                 'navTextColor' =>  '#7085F4',
  438.                 'navActiveColor' => '#7085F4',
  439.                 'linkColor' => '#7085F4',
  440.                 'linkHoverColor' => '#7085F4',
  441.                 'headerLinks' => null,
  442.                 'footerLinks' => null,
  443.                 'articleTextColor' => '#7085F4',
  444.                 'whiteList' => null,
  445.                 'blackList' => null,
  446.                 'siteDescritption' => 'Hi! how can i help you.',
  447.                 'metaDescription' => null,
  448.                 'metaKeywords' => null,
  449.                 'homepageContent' => null,
  450.                 'ticketCreateOption' =>  1,
  451.                 'createdAt' =>  '2018-09-21 16:20:01',
  452.                 'updatedat' =>  '2018-09-21 16:20:01',
  453.                 'broadcastMessage' => null,
  454.                 'removeCustomerLoginButton' => null,
  455.                 'disableCustomerlogin' =>  0,
  456.                 'removeBrandingContent' => null,
  457.                 'loginRequiredToCreate' => null,
  458.                 'script' => null,
  459.                 'customCss' => null,
  460.                 'isActive' => 1,
  461.             ];
  462.         }
  463.         
  464.         $website $this->entityManager->getRepository(Website::class)->findOneByCode($code);
  465.         if ($website) {
  466.             $configuration $this->entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy([
  467.                 'website' => $website->getId(), 
  468.                 'isActive' => 1
  469.             ]);
  470.         }
  471.         return !empty($configuration) ? $configuration false;
  472.     }
  473.     public function getWebsiteDetails($code)
  474.     {
  475.         $website $this->entityManager->getRepository(Website::class)->findOneByCode($code);
  476.         return !empty($website) ? $website false;
  477.     }
  478.     public function convertToTimezone($date$format "d-m-Y H:ia")
  479.     {
  480.         if(!$date)
  481.             return "N/A";
  482.         $currentUser $this->getCurrentUser();
  483.         $date date_format($date,$format);
  484.         $dateTime date('Y-m-d H:i:s',strtotime($date));
  485.         $scheduleDate = new \DateTime($dateTime, new \DateTimeZone(date_default_timezone_get()));
  486.         $this->domain $this->container->get('router')->getContext()->getHost();
  487.         $scheduleDate->setTimeZone(new \DateTimeZone('Asia/Kolkata'));
  488.         return $scheduleDate->format($format);
  489.     }
  490.     public function convertToDatetimeTimezoneTimestamp($date$format "d-m-Y h:ia")
  491.     {
  492.         if(!$date)
  493.             return "N/A";
  494.         $currentUser $this->getCurrentUser();
  495.         $date date_format($date$format);
  496.         $dateTime date('Y-m-d H:i:s',strtotime($date));
  497.         $scheduleDate = new \DateTime($dateTime, new \DateTimeZone(date_default_timezone_get()));
  498.         $this->domain $this->container->get('router')->getContext()->getHost();
  499.         $scheduleDate->setTimeZone(new \DateTimeZone('Asia/Kolkata'));
  500.         return $scheduleDate->getTimestamp();
  501.     }
  502.     public function removeCustomer($customer)
  503.     {
  504.         $userData $this->entityManager->getRepository(UserInstance::class)->findBy(array('user' => $customer->getId()));
  505.         $count count($userData);
  506.         $ticketData $this->entityManager->getRepository(Ticket::class)->findBy(array('customer' => $customer->getId()));
  507.         $fileService = new Fileservice();
  508.         // Delete all tickets attachments.
  509.         if($ticketData) {
  510.             foreach($ticketData as $ticket) {
  511.                 $threads $ticket->getThreads();
  512.                 if (count($threads) > 0) {
  513.                     foreach($threads as $thread) {
  514.                         if (!empty($thread)) {
  515.                             $fileService->remove($this->container->getParameter('kernel.project_dir').'/public/assets/threads/'.$thread->getId());
  516.                         }
  517.                     }
  518.                 }
  519.             }
  520.         }
  521.         // Remove profile.
  522.         foreach($userData as $user) {
  523.             if($user->getSupportRole()->getId() == && $user->getProfileImagePath()) {
  524.                 $fileService->remove($this->container->getParameter('kernel.project_dir').'/public'.$user->getProfileImagePath());
  525.             }
  526.         }
  527.         // getCustomerTickets
  528.         $qb $this->entityManager->createQueryBuilder();
  529.         $query $qb->delete(Ticket::class, 't')
  530.                     ->andwhere('t.customer = :customerId')
  531.                     ->setParameter('customerId'$customer->getId())
  532.                     ->getQuery();
  533.         $query->execute();
  534.         $qb $this->entityManager->createQueryBuilder();
  535.         $query $qb->delete(UserInstance::class, 'userInstance')
  536.                     ->andwhere('userInstance.user = :customerId')
  537.                     ->andwhere('userInstance.supportRole = :roleId')
  538.                     ->setParameter('customerId'$customer->getId())
  539.                     ->setParameter('roleId'4)
  540.                     ->getQuery();
  541.         $query->execute();
  542.         if($count == 1) {
  543.             $this->entityManager->remove($customer);
  544.             $this->entityManager->flush();
  545.         }
  546.     }
  547.     
  548.     public function removeAgent($user)
  549.     {
  550.         $userData $this->entityManager->getRepository(UserInstance::class)->findBy(array('user' => $user->getId()));
  551.         $count count($userData);
  552.         $qb $this->entityManager->createQueryBuilder();
  553.         $query $qb->delete(UserInstance::class, 'ud')
  554.                     ->andwhere('ud.user = :userId')
  555.                     ->andwhere('ud.supportRole = :roleId')
  556.                     ->setParameter('userId'$user->getId())
  557.                     ->setParameter('roleId'3)
  558.                     ->getQuery();
  559.         $query->execute();
  560.         
  561.         foreach ($user->getAgentInstance()->getSupportGroups() as $group) {
  562.                 $user->getAgentInstance()->removeSupportGroup($group);
  563.                 $this->entityManager->persist($group);
  564.                 $this->entityManager->flush();
  565.             
  566.         }
  567.         $qb $this->entityManager->createQueryBuilder();
  568.         $query $qb->update(Ticket::class, 't')
  569.                     ->set('t.agent'':nullAgent')
  570.                     ->andwhere('t.agent = :agentId')
  571.                     ->setParameter('agentId'$user->getId())
  572.                     ->setParameter('nullAgent'null)
  573.                     ->getQuery();
  574.         $query->execute();
  575.        
  576.         if($count == 1) {
  577.             $this->entityManager->remove($user);
  578.             $this->entityManager->flush();
  579.         }
  580.     }
  581.     public function getWebsiteView()
  582.     {
  583.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code'=>'knowledgebase']);
  584.         $layout  $this->entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy(['website'=>$website->getId()]);
  585.       
  586.         $homepageContent $layout->getHomepageContent();
  587.         return (!empty($homepageContent)) ? $homepageContent 'View' 'masonryView';
  588.     }
  589.     public function getUserDetailById($userId) {
  590.         $user $this->entityManager->getRepository(User::class)->find($userId);
  591.         foreach ($user->getUserInstance() as $row) {
  592.             if($row->getSupportRole()->getId() != 4)
  593.                 return $row;
  594.         }
  595.         return null;
  596.     }
  597.     public function getUserPrivilegeIds($userId
  598.     {
  599.         $qb $this->entityManager->createQueryBuilder();
  600.         $qb->select('supportPrivileges.id')->from(User::class, 'user')
  601.                 ->leftJoin('user.userInstance','userInstance')
  602.                 ->leftJoin('userInstance.supportPrivileges','supportPrivileges')
  603.                 ->andwhere('user.id = :userId')
  604.                 ->setParameter('userId'$userId);
  605.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  606.     }
  607.     public function getWebsiteSpamDetails($websiteSpam
  608.     {
  609.         $blackList str_replace("\n"','str_replace("\r\n"','$websiteSpam->getBlackList()));
  610.         $whiteList str_replace("\n"','str_replace("\r\n"','$websiteSpam->getWhiteList()));
  611.         return [
  612.             'blackList' => $this->filterBlockSpam($blackList),
  613.             'whiteList' => $this->filterBlockSpam($whiteList),
  614.         ];
  615.     }
  616.     public function filterBlockSpam($str
  617.     {
  618.         $list = array();
  619.         foreach (explode(','$str) as $value) {
  620.             if (filter_var($valueFILTER_VALIDATE_EMAIL)) {
  621.                 if (!isset($list['email'])) {
  622.                     $list['email'] = array();
  623.                 }
  624.                 array_push($list['email'], strtolower($value));
  625.             } else if (filter_var($valueFILTER_VALIDATE_IP)) {
  626.                 if (!isset($list['ip'])) {
  627.                     $list['ip'] = array();
  628.                 }
  629.                 
  630.                 array_push($list['ip'], $value);
  631.             } else if (isset($value[0]) && $value[0] == '@') {
  632.                 if (!isset($list['domain'])) {
  633.                     $list['domain'] = array();
  634.                 }
  635.                 array_push($list['domain'], strtolower($value));
  636.             }
  637.         }
  638.         
  639.         return $list;
  640.     }
  641.     // @TODO: Refactor this - We can instead just use \DateTimeZone::listIdentifiers() wherever need be.
  642.     public function getTimezones()
  643.     {
  644.         return \DateTimeZone::listIdentifiers();
  645.     }
  646.     public function getUserSavedReplyReferenceIds()
  647.     {
  648.         // @TODO: Refactor this function
  649.         $savedReplyIds = [];
  650.         $groupIds = [];
  651.         $teamIds = []; 
  652.         $userId $this->getCurrentUser()->getAgentInstance()->getId();
  653.         // Get all the saved reply the current user has created.
  654.         $savedReplyRepo $this->entityManager->getRepository(SavedReplies::class)->findAll();
  655.         foreach ($savedReplyRepo as $sr) {
  656.             if ($userId == $sr->getUser()->getId()) {
  657.                 //Save the ids of the saved reply.
  658.                 array_push($savedReplyIds, (int)$sr->getId());
  659.             }
  660.         }
  661.         // Get the ids of the Group(s) the current user is associated with.
  662.         $query "select * from uv_user_support_groups where userInstanceId =".$userId;
  663.         $connection $this->entityManager->getConnection();
  664.         $stmt $connection->prepare($query);
  665.         $stmt->execute();
  666.         $result $stmt->fetchAll();
  667.         foreach ($result as $row) {
  668.             array_push($groupIds$row['supportGroupId']);
  669.         }
  670.         // Get all the saved reply's ids that is associated with the user's group(s).
  671.         $query "select * from uv_saved_replies_groups";
  672.         $stmt $connection->prepare($query);
  673.         $stmt->execute();
  674.         $result $stmt->fetchAll();
  675.         foreach ($result as $row) {
  676.             if (in_array($row['group_id'], $groupIds)) {
  677.                 array_push($savedReplyIds, (int) $row['savedReply_id']);
  678.             }
  679.         }
  680.         // Get the ids of the Team(s) the current user is associated with.
  681.         $query "select * from uv_user_support_teams";
  682.         $connection $this->entityManager->getConnection();
  683.         $stmt $connection->prepare($query);
  684.         $stmt->execute();
  685.         $result $stmt->fetchAll();
  686.         foreach($result as $row) {
  687.             if ($row['userInstanceId'] == $userId) {
  688.                 array_push($teamIds$row['supportTeamId']);
  689.             }
  690.         }
  691.         $query "select * from uv_saved_replies_teams";
  692.         $stmt $connection->prepare($query);
  693.         $stmt->execute();
  694.         $result $stmt->fetchAll();
  695.         foreach ($result as $row) {
  696.             if (in_array($row['subgroup_id'], $teamIds)) {
  697.                 array_push($savedReplyIds, (int)$row['savedReply_id']);
  698.             }
  699.         }
  700.         return $savedReplyIds;
  701.     }
  702.     
  703.     // Return formatted time on user preference basis
  704.     public function getLocalizedFormattedTime(\DateTime $timestamp$user null$format 'm-d-y h:i A')
  705.     {
  706.         $activeUserTimeZone $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'Knowledgebase']);
  707.         if (!empty($user) && $user != 'anon.' && $user->getTimezone() != null) {
  708.             $timestamp = clone $timestamp;
  709.             
  710.             $timestamp->setTimeZone(new \DateTimeZone($user->getTimeZone()));
  711.             $format $user->getTimeFormat();
  712.         }elseif (!empty($activeUserTimeZone) && $activeUserTimeZone != 'anon.' && $activeUserTimeZone->getTimezone() != null) {
  713.             $timestamp = clone $timestamp;
  714.             
  715.             $timestamp->setTimeZone(new \DateTimeZone($activeUserTimeZone->getTimeZone()));
  716.             $format $activeUserTimeZone->getTimeFormat();
  717.         }
  718.         
  719.         return $timestamp->format($format);
  720.     }
  721.     public function isfileExists($filePath)
  722.     {
  723.         $dir $this->container->get('kernel')->getProjectDir();
  724.         // $dirSplit = explode('vendor', $dir);
  725.         $file str_replace("\\",'/'$dir."/".$filePath);
  726.         if (is_dir($file)) { 
  727.             return true;
  728.         }
  729.         
  730.         return false;
  731.     }
  732.     public function getCustomersCountForKudos($container)
  733.     {
  734.         $qb $this->entityManager->createQueryBuilder();
  735.         $qb->select($qb->expr()->countDistinct('c.id')."as customerCount")->from(Ticket::class, 't')
  736.                 ->leftJoin('t.customer''c');
  737.         $container->get('report.service')->addPermissionFilter($qb$this->containerfalse);
  738.         return $qb->getQuery()->getSingleScalarResult();
  739.     }
  740. }