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