vendor/uvdesk/core-framework/Services/UserService.php line 83

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