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

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.             $eventId 'ROLE_CUSTOMER' == $role->getCode() ? CoreWorkflowEvents\Customer\Create::getId() : CoreWorkflowEvents\Agent\Create::getId();
  231.             $event = new GenericEvent($eventId, ['entity' => $user]);
  232.             $this->container->get('event_dispatcher')->dispatch($event'uvdesk.automation.workflow.execute');
  233.         }
  234.         return $user;
  235.     }
  236.     public function getAgentPartialDataCollection(Request $request null)
  237.     {
  238.         $queryBuilder $this->entityManager->createQueryBuilder()
  239.             ->select("user.id, user.email, CONCAT(user.firstName, ' ', COALESCE(user.lastName, '')) as name, userInstance.profileImagePath as smallThumbnail")
  240.             ->from(User::class, 'user')
  241.             ->leftJoin('user.userInstance''userInstance')
  242.             ->leftJoin('userInstance.supportRole''supportRole')
  243.             ->where('supportRole.code != :customerRole')->setParameter('customerRole''ROLE_CUSTOMER')
  244.             ->andWhere('userInstance.isActive = :isUserActive')->setParameter('isUserActive'true)
  245.             ->orderBy('name'Criteria::ASC);
  246.         if ($request && null != $request->query->get('query')) {
  247.             $queryBuilder
  248.                 ->andWhere("CONCAT(user.firstName,' ', user.lastName) LIKE :customerName")
  249.                 ->setParameter('customerName''%'.urldecode($request->query->get('query')).'%');
  250.         }
  251.         if ($request && null != $request->query->get('not')) {
  252.             $queryBuilder
  253.                 ->andwhere("u.id NOT IN (:ids)")
  254.                 ->setParameter('ids'explode(','urldecode($request->query->get('not'))));
  255.         }
  256.         return $queryBuilder->getQuery()->getArrayResult();
  257.     }
  258.     public function getAgentsPartialDetails(Request $request null) {
  259.         static $agents;
  260.         if (null !== $agents)
  261.             return $agents;
  262.         $qb $this->entityManager->createQueryBuilder();
  263.         $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')
  264.                 ->leftJoin('u.userInstance''userInstance')
  265.                 ->andwhere('userInstance.supportRole != :roles')
  266.                 ->setParameter('roles'4)
  267.                 ->andwhere('userInstance.isActive = 1')
  268.                 ->orderBy('name','ASC');
  269.         if($request) {
  270.             $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName");
  271.             $qb->setParameter('customerName''%'.urldecode($request->query->get('query')).'%');
  272.             $qb->andwhere("u.id NOT IN (:ids)");
  273.             $qb->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  274.         }
  275.         $data $agents $qb->getQuery()->getArrayResult();
  276.         return $data;
  277.     }
  278.     public function getAgentDetailById($agentId) {
  279.         if(!$agentId) return;
  280.         $qb $this->entityManager->createQueryBuilder();
  281.         $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")
  282.             ->from(User::class, 'u')
  283.             ->leftJoin('u.userInstance''userInstance')
  284.             ->andwhere('userInstance.supportRole != :roles')
  285.             ->andwhere('u.id = :agentId')
  286.             ->setParameter('roles'4)
  287.             ->setParameter('agentId'$agentId);
  288.         $result $qb->getQuery()->getResult();
  289.         return isset($result[0]) ? $result[0] : null;
  290.     }
  291.     public function getUsersByGroupId($groupId)
  292.     {
  293.         $qb $this->entityManager->createQueryBuilder();
  294.         $qb->select("DISTINCT user.id, user.email, CONCAT(user.firstName, ' ', user.lastName) AS name, userInstance.profileImagePath as smallThumbnail")
  295.             ->from(User::class, 'user')
  296.             ->leftJoin('user.userInstance''userInstance')
  297.                 ->leftJoin('userInstance.supportGroups''supportGroup')
  298.                 ->andWhere('userInstance.supportRole != :roles')->setParameter('roles'4)
  299.                 ->andwhere('supportGroup.id = :groupId')->setParameter('groupId'$groupId)
  300.                 ->andwhere('userInstance.isActive = 1');
  301.         $data $qb->getQuery()->getArrayResult();
  302.         return $data;
  303.     }
  304.     public function getUsersBySubGroupId($subGroupId)
  305.     {
  306.         $qb $this->entityManager->createQueryBuilder();
  307.         $qb->select("DISTINCT user.id, supportTeam.id as udId,user.email,CONCAT(user.firstName,' ', user.lastName) AS name,userInstance.profileImagePath as smallThumbnail")
  308.                 ->from(User::class, 'user')
  309.                 ->leftJoin('user.userInstance''userInstance')
  310.                 ->leftJoin('userInstance.supportTeams''supportTeam')
  311.                 ->andwhere('userInstance.supportRole != :roles')
  312.                 ->andwhere('supportTeam.id = :subGroupId')
  313.                 ->setParameter('roles'4)
  314.                 ->setParameter('subGroupId'$subGroupId)
  315.                 ->andwhere('supportTeam.isActive = 1')
  316.                 ->andwhere('userInstance.isActive = 1');
  317.         $data $qb->getQuery()->getArrayResult();
  318.         return $data;
  319.     }
  320.     public function getCustomerDetailsById($customerId)
  321.     {
  322.         $qb $this->entityManager->createQueryBuilder();
  323.         $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')
  324.                 ->leftJoin('user.userInstance''userInstance')
  325.                 ->andwhere('userInstance.supportRole = :roles')
  326.                 ->andwhere('user.id = :customerId')
  327.                 ->setParameter('roles'4)
  328.                 ->setParameter('customerId'$customerId);
  329.         $result $qb->getQuery()->getResult();
  330.         return ($result $result[0] : null);
  331.     }
  332.     public function getCustomerPartialDetailById($customerId)
  333.     {
  334.         $qb $this->entityManager->createQueryBuilder();
  335.         $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')
  336.             ->leftJoin('u.userInstance''userInstance')
  337.             ->andwhere('userInstance.supportRole = :roles')
  338.             ->andwhere('u.id = :customerId')
  339.             ->setParameter('roles'4)
  340.             ->setParameter('customerId'$customerId);
  341.         $result $qb->getQuery()->getResult();
  342.         return $result $result[0] : null;
  343.     }
  344.     public function getCustomersPartial(Request $request null)
  345.     {
  346.         $qb $this->entityManager->createQueryBuilder();
  347.         $qb->from(User::class, 'u');
  348.         $qb->select("DISTINCT u.id,CONCAT(u.firstName,' ', COALESCE(u.lastName,'')) AS name, userInstance.profileImagePath as smallThumbnail ")
  349.             ->leftJoin('u.userInstance''userInstance')
  350.             ->andwhere('userInstance.supportRole = :roles')
  351.             ->setParameter('roles'4)
  352.             ->orderBy('name','ASC');
  353.         
  354.         if ($request) {
  355.             if ($request->query->get('query')) {
  356.                 $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName OR u.email LIKE :customerName");
  357.             } else {
  358.                 $qb->andwhere("CONCAT(u.firstName,' ', u.lastName) LIKE :customerName");
  359.             }
  360.             
  361.             $qb->setParameter('customerName''%'.urldecode($request->query->get('query')).'%')
  362.                 ->andwhere("u.id NOT IN (:ids)")
  363.                 ->setParameter('ids'explode(',',urldecode($request->query->get('not'))));
  364.         }
  365.         $query $qb->getQuery();
  366.         // $query->useResultCache(true, 3600, 'customer_list_'.$this->getCompany()->getId());
  367.         return $query->getScalarResult();
  368.     }
  369.     public function getCustomersCount()
  370.     {
  371.         $qb $this->entityManager->createQueryBuilder();
  372.         $qb->select($qb->expr()->countDistinct('c.id')."as customerCount")->from(Ticket::class, 't')
  373.                 ->leftJoin('t.customer''c');
  374.         $this->entityManager->getRepository(Ticket::class)->addPermissionFilter($qb$this->containerfalse);
  375.         return $qb->getQuery()->getSingleScalarResult();
  376.     }
  377.     public function getUserSubGroupIds($userId) {
  378.         $qb $this->entityManager->createQueryBuilder();
  379.         $qb->select('supportTeams.id')->from(User::class, 'user')
  380.                 ->leftJoin('user.userInstance','userInstance')
  381.                 ->leftJoin('userInstance.supportTeams','supportTeams')
  382.                 ->andwhere('user.id = :userId')
  383.                 ->andwhere('userInstance.supportRole != :agentRole')
  384.                 ->andwhere('supportTeams.isActive = 1')
  385.                 ->setParameter('userId'$userId)
  386.                 ->setParameter('agentRole''4'); 
  387.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  388.     }
  389.     public function getUserGroupIds($userId) {
  390.         $qb $this->entityManager->createQueryBuilder();
  391.         $qb->select('supportGroup.id')->from(User::class, 'user')
  392.                 ->leftJoin('user.userInstance','userInstance')
  393.                 ->leftJoin('userInstance.supportGroups','supportGroup')
  394.                 ->andwhere('user.id = :userId')
  395.                 ->andwhere('supportGroup.isActive = 1')
  396.                 ->setParameter('userId'$userId);
  397.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  398.     }
  399.     public function createUser($data)
  400.     {
  401.         $user = new User();
  402.         $user->setEmail($data['from']);
  403.         $user->setFirstName($data['firstName']);
  404.         $user->setLastName($data['lastName']);
  405.         $user->setIsEnabled($data['isActive']);
  406.         $this->entityManager->persist($user);
  407.         // $this->entityManager->flush();
  408.         $role $this->entityManager->getRepository(SupportRole::class)->find($data['role']);
  409.     
  410.         $userInstance = new UserInstance();
  411.         $userInstance->setSupportRole($role);
  412.         $userInstance->setUser($user);
  413.         $userInstance->setIsActive($data['isActive']);
  414.         $userInstance->setIsVerified(0);
  415.         if(isset($data['source']))
  416.             $userInstance->setSource($data['source']);
  417.         else
  418.             $userInstance->setSource('website');
  419.         if(isset($data['contactNumber'])) {
  420.             $userInstance->setContactNumber($data['contactNumber']);
  421.         }
  422.         if(isset($data['profileImage']) && $data['profileImage']) {
  423.                 $userInstance->setProfileImagePath($data['profileImage']);
  424.         }
  425.         $this->entityManager->persist($userInstance);
  426.         $this->entityManager->flush();
  427.         $user->addUserInstance($userInstance);
  428.         $this->entityManager->persist($user);
  429.         $this->entityManager->flush();
  430.         //$user->setUserName($userInstance->getName());
  431.         return $user;
  432.     }
  433.     public function getWebsiteConfiguration($code)
  434.     {
  435.         $enabled_bundles $this->container->getParameter('kernel.bundles');
  436.         
  437.         if (!in_array('UVDeskSupportCenterBundle'array_keys($enabled_bundles))) {
  438.             return [
  439.                 'id' =>  1,
  440.                 'website' =>  1,
  441.                 'status' =>  1,
  442.                 'brandColor' => '#7E91F0',
  443.                 'pageBackgroundColor' => '#FFFFFF',
  444.                 'headerBackgroundColor' => '#FFFFFF',
  445.                 'bannerBackgroundColor' => '#7085F4',
  446.                 'navTextColor' =>  '#7085F4',
  447.                 'navActiveColor' => '#7085F4',
  448.                 'linkColor' => '#7085F4',
  449.                 'linkHoverColor' => '#7085F4',
  450.                 'headerLinks' => null,
  451.                 'footerLinks' => null,
  452.                 'articleTextColor' => '#7085F4',
  453.                 'whiteList' => null,
  454.                 'blackList' => null,
  455.                 'siteDescritption' => 'Hi! how can i help you.',
  456.                 'metaDescription' => null,
  457.                 'metaKeywords' => null,
  458.                 'homepageContent' => null,
  459.                 'ticketCreateOption' =>  1,
  460.                 'createdAt' =>  '2018-09-21 16:20:01',
  461.                 'updatedat' =>  '2018-09-21 16:20:01',
  462.                 'broadcastMessage' => null,
  463.                 'removeCustomerLoginButton' => null,
  464.                 'disableCustomerlogin' =>  0,
  465.                 'removeBrandingContent' => null,
  466.                 'loginRequiredToCreate' => null,
  467.                 'script' => null,
  468.                 'customCss' => null,
  469.                 'isActive' => 1,
  470.             ];
  471.         }
  472.         
  473.         $website $this->entityManager->getRepository(Website::class)->findOneByCode($code);
  474.         if ($website) {
  475.             $configuration $this->entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy([
  476.                 'website' => $website->getId(), 
  477.                 'isActive' => 1
  478.             ]);
  479.         }
  480.         return !empty($configuration) ? $configuration false;
  481.     }
  482.     public function getWebsiteDetails($code)
  483.     {
  484.         $website $this->entityManager->getRepository(Website::class)->findOneByCode($code);
  485.         return !empty($website) ? $website false;
  486.     }
  487.     public function convertToTimezone($date$format "d-m-Y H:ia")
  488.     {
  489.         if(!$date)
  490.             return "N/A";
  491.         $currentUser $this->getCurrentUser();
  492.         $date date_format($date,$format);
  493.         $dateTime date('Y-m-d H:i:s',strtotime($date));
  494.         $scheduleDate = new \DateTime($dateTime, new \DateTimeZone(date_default_timezone_get()));
  495.         $this->domain $this->container->get('router')->getContext()->getHost();
  496.         $scheduleDate->setTimeZone(new \DateTimeZone('Asia/Kolkata'));
  497.         return $scheduleDate->format($format);
  498.     }
  499.     public function convertToDatetimeTimezoneTimestamp($date$format "d-m-Y h:ia")
  500.     {
  501.         if(!$date)
  502.             return "N/A";
  503.         $currentUser $this->getCurrentUser();
  504.         $date date_format($date$format);
  505.         $dateTime date('Y-m-d H:i:s',strtotime($date));
  506.         $scheduleDate = new \DateTime($dateTime, new \DateTimeZone(date_default_timezone_get()));
  507.         $this->domain $this->container->get('router')->getContext()->getHost();
  508.         $scheduleDate->setTimeZone(new \DateTimeZone('Asia/Kolkata'));
  509.         return $scheduleDate->getTimestamp();
  510.     }
  511.     public function removeCustomer($customer)
  512.     {
  513.         $userData $this->entityManager->getRepository(UserInstance::class)->findBy(array('user' => $customer->getId()));
  514.         $count count($userData);
  515.         $ticketData $this->entityManager->getRepository(Ticket::class)->findBy(array('customer' => $customer->getId()));
  516.         $fileService = new Fileservice();
  517.         // Delete all tickets attachments.
  518.         if($ticketData) {
  519.             foreach($ticketData as $ticket) {
  520.                 $threads $ticket->getThreads();
  521.                 if (count($threads) > 0) {
  522.                     foreach($threads as $thread) {
  523.                         if (!empty($thread)) {
  524.                             $fileService->remove($this->container->getParameter('kernel.project_dir').'/public/assets/threads/'.$thread->getId());
  525.                         }
  526.                     }
  527.                 }
  528.             }
  529.         }
  530.         // Remove profile.
  531.         foreach($userData as $user) {
  532.             if($user->getSupportRole()->getId() == && $user->getProfileImagePath()) {
  533.                 $fileService->remove($this->container->getParameter('kernel.project_dir').'/public'.$user->getProfileImagePath());
  534.             }
  535.         }
  536.         // getCustomerTickets
  537.         $qb $this->entityManager->createQueryBuilder();
  538.         $query $qb->delete(Ticket::class, 't')
  539.                     ->andwhere('t.customer = :customerId')
  540.                     ->setParameter('customerId'$customer->getId())
  541.                     ->getQuery();
  542.         $query->execute();
  543.         $qb $this->entityManager->createQueryBuilder();
  544.         $query $qb->delete(UserInstance::class, 'userInstance')
  545.                     ->andwhere('userInstance.user = :customerId')
  546.                     ->andwhere('userInstance.supportRole = :roleId')
  547.                     ->setParameter('customerId'$customer->getId())
  548.                     ->setParameter('roleId'4)
  549.                     ->getQuery();
  550.         $query->execute();
  551.         if($count == 1) {
  552.             $this->entityManager->remove($customer);
  553.             $this->entityManager->flush();
  554.         }
  555.     }
  556.     
  557.     public function removeAgent($user)
  558.     {
  559.         $userData $this->entityManager->getRepository(UserInstance::class)->findBy(array('user' => $user->getId()));
  560.         $count count($userData);
  561.         $qb $this->entityManager->createQueryBuilder();
  562.         $query $qb->delete(UserInstance::class, 'ud')
  563.                     ->andwhere('ud.user = :userId')
  564.                     ->andwhere('ud.supportRole = :roleId')
  565.                     ->setParameter('userId'$user->getId())
  566.                     ->setParameter('roleId'3)
  567.                     ->getQuery();
  568.         $query->execute();
  569.         
  570.         foreach ($user->getAgentInstance()->getSupportGroups() as $group) {
  571.                 $user->getAgentInstance()->removeSupportGroup($group);
  572.                 $this->entityManager->persist($group);
  573.                 $this->entityManager->flush();
  574.             
  575.         }
  576.         $qb $this->entityManager->createQueryBuilder();
  577.         $query $qb->update(Ticket::class, 't')
  578.                     ->set('t.agent'':nullAgent')
  579.                     ->andwhere('t.agent = :agentId')
  580.                     ->setParameter('agentId'$user->getId())
  581.                     ->setParameter('nullAgent'null)
  582.                     ->getQuery();
  583.         $query->execute();
  584.        
  585.         if($count == 1) {
  586.             $this->entityManager->remove($user);
  587.             $this->entityManager->flush();
  588.         }
  589.     }
  590.     public function getWebsiteView()
  591.     {
  592.         $website $this->entityManager->getRepository(Website::class)->findOneBy(['code'=>'knowledgebase']);
  593.         $layout  $this->entityManager->getRepository(KnowledgebaseWebsite::class)->findOneBy(['website'=>$website->getId()]);
  594.       
  595.         $homepageContent $layout->getHomepageContent();
  596.         return (!empty($homepageContent)) ? $homepageContent 'View' 'masonryView';
  597.     }
  598.     public function getUserDetailById($userId) {
  599.         $user $this->entityManager->getRepository(User::class)->find($userId);
  600.         foreach ($user->getUserInstance() as $row) {
  601.             if($row->getSupportRole()->getId() != 4)
  602.                 return $row;
  603.         }
  604.         return null;
  605.     }
  606.     public function getUserPrivilegeIds($userId
  607.     {
  608.         $qb $this->entityManager->createQueryBuilder();
  609.         $qb->select('supportPrivileges.id')->from(User::class, 'user')
  610.                 ->leftJoin('user.userInstance','userInstance')
  611.                 ->leftJoin('userInstance.supportPrivileges','supportPrivileges')
  612.                 ->andwhere('user.id = :userId')
  613.                 ->setParameter('userId'$userId);
  614.         return array_column($qb->getQuery()->getArrayResult(), 'id');
  615.     }
  616.     public function getWebsiteSpamDetails($websiteSpam
  617.     {
  618.         $blackList str_replace("\n"','str_replace("\r\n"','$websiteSpam->getBlackList()));
  619.         $whiteList str_replace("\n"','str_replace("\r\n"','$websiteSpam->getWhiteList()));
  620.         return [
  621.             'blackList' => $this->filterBlockSpam($blackList),
  622.             'whiteList' => $this->filterBlockSpam($whiteList),
  623.         ];
  624.     }
  625.     public function filterBlockSpam($str
  626.     {
  627.         $list = array();
  628.         foreach (explode(','$str) as $value) {
  629.             if (filter_var($valueFILTER_VALIDATE_EMAIL)) {
  630.                 if (!isset($list['email'])) {
  631.                     $list['email'] = array();
  632.                 }
  633.                 array_push($list['email'], strtolower($value));
  634.             } else if (filter_var($valueFILTER_VALIDATE_IP)) {
  635.                 if (!isset($list['ip'])) {
  636.                     $list['ip'] = array();
  637.                 }
  638.                 
  639.                 array_push($list['ip'], $value);
  640.             } else if (isset($value[0]) && $value[0] == '@') {
  641.                 if (!isset($list['domain'])) {
  642.                     $list['domain'] = array();
  643.                 }
  644.                 array_push($list['domain'], strtolower($value));
  645.             }
  646.         }
  647.         
  648.         return $list;
  649.     }
  650.     // @TODO: Refactor this - We can instead just use \DateTimeZone::listIdentifiers() wherever need be.
  651.     public function getTimezones()
  652.     {
  653.         return \DateTimeZone::listIdentifiers();
  654.     }
  655.     public function getUserSavedReplyReferenceIds()
  656.     {
  657.         // @TODO: Refactor this function
  658.         $savedReplyIds = [];
  659.         $groupIds = [];
  660.         $teamIds = []; 
  661.         $userId $this->getCurrentUser()->getAgentInstance()->getId();
  662.         // Get all the saved reply the current user has created.
  663.         $savedReplyRepo $this->entityManager->getRepository(SavedReplies::class)->findAll();
  664.         foreach ($savedReplyRepo as $sr) {
  665.             if ($userId == $sr->getUser()->getId()) {
  666.                 //Save the ids of the saved reply.
  667.                 array_push($savedReplyIds, (int)$sr->getId());
  668.             }
  669.         }
  670.         // Get the ids of the Group(s) the current user is associated with.
  671.         $query "select * from uv_user_support_groups where userInstanceId =".$userId;
  672.         $connection $this->entityManager->getConnection();
  673.         $stmt $connection->prepare($query);
  674.         $stmt->execute();
  675.         $result $stmt->fetchAll();
  676.         foreach ($result as $row) {
  677.             array_push($groupIds$row['supportGroupId']);
  678.         }
  679.         // Get all the saved reply's ids that is associated with the user's group(s).
  680.         $query "select * from uv_saved_replies_groups";
  681.         $stmt $connection->prepare($query);
  682.         $stmt->execute();
  683.         $result $stmt->fetchAll();
  684.         foreach ($result as $row) {
  685.             if (in_array($row['group_id'], $groupIds)) {
  686.                 array_push($savedReplyIds, (int) $row['savedReply_id']);
  687.             }
  688.         }
  689.         // Get the ids of the Team(s) the current user is associated with.
  690.         $query "select * from uv_user_support_teams";
  691.         $connection $this->entityManager->getConnection();
  692.         $stmt $connection->prepare($query);
  693.         $stmt->execute();
  694.         $result $stmt->fetchAll();
  695.         foreach($result as $row) {
  696.             if ($row['userInstanceId'] == $userId) {
  697.                 array_push($teamIds$row['supportTeamId']);
  698.             }
  699.         }
  700.         $query "select * from uv_saved_replies_teams";
  701.         $stmt $connection->prepare($query);
  702.         $stmt->execute();
  703.         $result $stmt->fetchAll();
  704.         foreach ($result as $row) {
  705.             if (in_array($row['subgroup_id'], $teamIds)) {
  706.                 array_push($savedReplyIds, (int)$row['savedReply_id']);
  707.             }
  708.         }
  709.         return $savedReplyIds;
  710.     }
  711.     
  712.     // Return formatted time on user preference basis
  713.     public function getLocalizedFormattedTime(\DateTime $timestamp$user null$format 'm-d-y h:i A')
  714.     {
  715.         $activeUserTimeZone $this->entityManager->getRepository(Website::class)->findOneBy(['code' => 'Knowledgebase']);
  716.         if (!empty($user) && $user != 'anon.' && $user->getTimezone() != null) {
  717.             $timestamp = clone $timestamp;
  718.             
  719.             $timestamp->setTimeZone(new \DateTimeZone($user->getTimeZone()));
  720.             $format $user->getTimeFormat();
  721.         }elseif (!empty($activeUserTimeZone) && $activeUserTimeZone != 'anon.' && $activeUserTimeZone->getTimezone() != null) {
  722.             $timestamp = clone $timestamp;
  723.             
  724.             $timestamp->setTimeZone(new \DateTimeZone($activeUserTimeZone->getTimeZone()));
  725.             $format $activeUserTimeZone->getTimeFormat();
  726.         }
  727.         
  728.         return $timestamp->format($format);
  729.     }
  730.     public function isfileExists($filePath)
  731.     {
  732.         $dir $this->container->get('kernel')->getProjectDir();
  733.         // $dirSplit = explode('vendor', $dir);
  734.         $file str_replace("\\",'/'$dir."/".$filePath);
  735.         if (is_dir($file)) { 
  736.             return true;
  737.         }
  738.         
  739.         return false;
  740.     }
  741.     public function getCustomersCountForKudos($container)
  742.     {
  743.         $qb $this->entityManager->createQueryBuilder();
  744.         $qb->select($qb->expr()->countDistinct('c.id')."as customerCount")->from(Ticket::class, 't')
  745.                 ->leftJoin('t.customer''c');
  746.         $container->get('report.service')->addPermissionFilter($qb$this->containerfalse);
  747.         return $qb->getQuery()->getSingleScalarResult();
  748.     }
  749. }