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

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