vendor/uvdesk/core-framework/Services/UVDeskService.php line 39

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Services;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Webkul\UVDesk\CoreFrameworkBundle\Utils\TokenGenerator;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. use Webkul\UVDesk\SupportCenterBundle\Entity\KnowledgebaseWebsite;
  10. use Webkul\UVDesk\CoreFrameworkBundle\Services\UserService;
  11. class UVDeskService
  12. {
  13. protected $container;
  14. protected $requestStack;
  15. protected $entityManager;
  16. private $avoidArray = [
  17. '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '/', '\\', ':', '{', '}', '[', ']', '<', '>', '.', '?', ';', '"', '\'', ',', '|',
  18. '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
  19. ' true ', ' false ',
  20. ' do ', ' did ',
  21. ' is ', ' are ', ' am ', ' was ', ' were ',
  22. ' has ', ' have ', ' had ',
  23. ' will ', ' would ', ' shall ', ' should ', ' must ', ' can ', ' could ',
  24. ' not ', ' never ',
  25. ' neither ', ' either ',
  26. ' the ', ' a ', ' an ', ' this ', ' that ',
  27. ' here ', ' there ',
  28. ' then ', ' when ', ' since ',
  29. ' he ', ' him ', ' himself ', ' she ', ' her ', ' herself ', ' i ', ' me ', ' myself ', ' mine ', ' you ', ' your ' ,' yourself ', ' ur ', ' we ', ' ourself ', ' it ', ' its ',
  30. ' for ', ' from ', ' on ', ' and ', ' in ', ' be ', ' to ', ' or ', ' of ', ' with ',
  31. ' what ', ' why ', ' where ', ' who ', ' whom ', ' which ',
  32. ' a ', ' b ', ' c ', ' d ', ' e ' , ' f ' , ' g ' , ' h ' , ' i ' , ' j ' , ' k ' , ' l ' , ' m ' , ' n ' , ' o ' , ' p ' , ' q ' , ' r ' , ' s ' , ' t ' , ' u ' , ' v ' , ' w ' , ' x ' , ' y ' , ' z ' ,
  33. ' ',
  34. ];
  35. public function __construct(ContainerInterface $container, RequestStack $requestStack, EntityManagerInterface $entityManager, UserService $userService)
  36. {
  37. $this->container = $container;
  38. $this->requestStack = $requestStack;
  39. $this->entityManager = $entityManager;
  40. $this->userService = $userService;
  41. }
  42. public function updatesLocales($locales)
  43. {
  44. $fileTranslation = $this->container->get('kernel')->getProjectDir() . '/config/packages/translation.yaml';
  45. $fileServices = $this->container->get('kernel')->getProjectDir() . '/config/services.yaml';
  46. // get file content and index
  47. $fileTrans = file($fileTranslation);
  48. $fileServs = file($fileServices);
  49. foreach ($fileTrans as $index => $content) {
  50. if (false !== strpos($content, 'default_locale')) {
  51. list($helpdesk_panel_locales, $helpdesk_panel_text) = array($index, $content);
  52. }
  53. if (false !== strpos($content, '- ')) {
  54. list($helpdesk_panel_locales_fallback, $helpdesk_panel_text_fallback) = array($index, $content);
  55. }
  56. }
  57. foreach ($fileServs as $indexs => $contents) {
  58. if (false !== strpos($contents, 'locale')) {
  59. list($helpdesk_services_locales, $helpdesk_services_text) = array($indexs, $contents);
  60. }
  61. }
  62. // save updated data in a variable ($updatedFileContent)
  63. $updatedFileContent = $fileTrans;
  64. $updatedServicesFileContent = $fileServs;
  65. $updatedlocales = (null !== $helpdesk_panel_locales) ? substr($helpdesk_panel_text, 0, strpos($helpdesk_panel_text, 'default_locale') + strlen('default_locale: ')) . $locales . PHP_EOL: '';
  66. $updatedlocales_fallback = (null !== $helpdesk_panel_locales_fallback) ? substr($helpdesk_panel_text_fallback, 0, strpos($helpdesk_panel_text_fallback, '- ') + strlen('- ')) . $locales . PHP_EOL: '';
  67. $updatedServiceslocales = (null !== $helpdesk_services_locales) ? substr($helpdesk_services_text, 0, strpos($helpdesk_services_text, 'locale') + strlen('locale: ')) . $locales . PHP_EOL: '';
  68. $updatedFileContent[$helpdesk_panel_locales] = $updatedlocales;
  69. $updatedFileContent[$helpdesk_panel_locales_fallback] = $updatedlocales_fallback;
  70. $updatedServicesFileContent[$helpdesk_services_locales] = $updatedServiceslocales;
  71. // flush updated content in file
  72. $status = file_put_contents($fileTranslation, $updatedFileContent);
  73. $status1 = file_put_contents($fileServices, $updatedServicesFileContent);
  74. return true;
  75. }
  76. public function getLocalesList()
  77. {
  78. $translator = $this->container->get('translator');
  79. return [
  80. 'en' => $translator->trans("English"),
  81. 'fr' => $translator->trans("French"),
  82. 'it' => $translator->trans("Italian"),
  83. 'ar' => $translator->trans("Arabic"),
  84. 'de' => $translator->trans("German"),
  85. 'es' => $translator->trans("Spanish"),
  86. 'tr' => $translator->trans("Turkish"),
  87. 'da' => $translator->trans("Danish"),
  88. 'zh' => $translator->trans("Chinese"),
  89. 'pl' => $translator->trans("Polish"),
  90. ];
  91. }
  92. public function getActiveLocales()
  93. {
  94. $localesList = $this->getLocalesList();
  95. $activeLocales = $this->container->getParameter("app_locales");
  96. $explodeActiveLocales = explode("|",$activeLocales);
  97. return $explodeActiveLocales;
  98. }
  99. public function getLocales()
  100. {
  101. $localesList = $this->getLocalesList();
  102. $explodeActiveLocales = $this->getActiveLocales();
  103. $listingActiveLocales = array();
  104. foreach ($explodeActiveLocales as $key => $value) {
  105. $listingActiveLocales[$value] = $localesList[$value];
  106. }
  107. return $listingActiveLocales;
  108. }
  109. public function getDefaultLangauge()
  110. {
  111. return $this->container->getParameter("kernel.default_locale");
  112. }
  113. public function getTimezones()
  114. {
  115. return \DateTimeZone::listIdentifiers();
  116. }
  117. public function getPrivileges() {
  118. $agentPrivilegeCollection = [];
  119. // $agentPrivilegeCollection = $this->entityManager->getRepository('UserBundle:AgentPrivilege')->findAll();
  120. return $agentPrivilegeCollection;
  121. }
  122. public function getLocaleUrl($locale)
  123. {
  124. $request = $this->requestStack->getCurrentRequest();
  125. return str_replace('/' . $request->getLocale() . '/', '/' . $locale . '/', $request->getRequestUri());
  126. }
  127. public function buildPaginationQuery(array $query = [])
  128. {
  129. $params = array();
  130. $query['page'] = "replacePage";
  131. if (isset($query['domain'])) unset($query['domain']);
  132. if (isset($query['_locale'])) unset($query['_locale']);
  133. foreach ($query as $key => $value) {
  134. $params[] = !isset($value) ? $key : $key . '/' . str_replace('%2F', '/', rawurlencode($value));
  135. }
  136. $http_query = implode('/', $params);
  137. if (isset($query['new'])) {
  138. $http_query = str_replace('new/1', 'new', $http_query);
  139. } else if (isset($query['unassigned'])) {
  140. $http_query = str_replace('unassigned/1', 'unassigned', $http_query);
  141. } else if (isset($query['notreplied'])) {
  142. $http_query = str_replace('notreplied/1', 'notreplied', $http_query);
  143. } else if (isset($query['mine'])) {
  144. $http_query = str_replace('mine/1', 'mine', $http_query);
  145. } else if (isset($query['starred'])) {
  146. $http_query = str_replace('starred/1', 'starred', $http_query);
  147. } else if (isset($query['trashed'])) {
  148. $http_query = str_replace('trashed/1', 'trashed', $http_query);
  149. }
  150. return $http_query;
  151. }
  152. public function getEntityManagerResult($entity, $callFunction, $args = false, $extraPrams = false)
  153. {
  154. if($extraPrams)
  155. return $this->entityManager->getRepository($entity)
  156. ->$callFunction($args, $extraPrams);
  157. else
  158. return $this->entityManager->getRepository($entity)
  159. ->$callFunction($args);
  160. }
  161. public function getValidBroadcastMessage($msg, $format = 'Y-m-d H:i:s')
  162. {
  163. $broadcastMessage = !empty($msg) ? json_decode($msg, true) : false;
  164. if(!empty($broadcastMessage) && isset($broadcastMessage['isActive']) && $broadcastMessage['isActive']) {
  165. $timezone = new \DateTimeZone('Asia/Kolkata');
  166. $nowTimestamp = date('U');
  167. if(array_key_exists('from', $broadcastMessage) && ($fromDateTime = \DateTime::createFromFormat($format, $broadcastMessage['from'], $timezone))) {
  168. $fromTimeStamp = $fromDateTime->format('U');
  169. if($nowTimestamp < $fromTimeStamp) {
  170. return false;
  171. }
  172. }
  173. if(array_key_exists('to', $broadcastMessage) && ($toDateTime = \DateTime::createFromFormat($format, $broadcastMessage['to'], $timezone))) {
  174. $toTimeStamp = $toDateTime->format('U');;
  175. if($nowTimestamp > $toTimeStamp) {
  176. return false;
  177. }
  178. }
  179. } else {
  180. return false;
  181. }
  182. // return valid broadcast message Array
  183. return $broadcastMessage;
  184. }
  185. public function getConfigParameter($param)
  186. {
  187. if($param && $this->container->hasParameter($param)) {
  188. return $this->container->getParameter($param);
  189. } else {
  190. return false;
  191. }
  192. }
  193. public function isDarkSkin($brandColor) {
  194. $brandColor = str_replace('#', '', $brandColor);
  195. if(strlen($brandColor) == 3)
  196. $brandColor .= $brandColor;
  197. $chars = str_split($brandColor);
  198. $a2fCount = 0;
  199. foreach ($chars as $key => $char) {
  200. if(in_array($key, [0, 2, 4]) && in_array(strtoupper($char), ['A', 'B', 'C', 'D', 'E', 'F'])) {
  201. $a2fCount++;
  202. }
  203. }
  204. if($a2fCount >= 2)
  205. return true;
  206. else
  207. return false;
  208. }
  209. public function getActiveConfiguration($websiteId)
  210. {
  211. $configurationRepo = $this->entityManager->getRepository(KnowledgebaseWebsite::class);
  212. $configuration = $configurationRepo->findOneBy(['website' => $websiteId, 'isActive' => 1]);
  213. return $configuration;
  214. }
  215. public function getSupportPrivelegesResources()
  216. {
  217. $translator = $this->container->get('translator');
  218. return [
  219. 'ticket' => [
  220. 'ROLE_AGENT_CREATE_TICKET' => $translator->trans('Can create ticket'),
  221. 'ROLE_AGENT_EDIT_TICKET' => $translator->trans('Can edit ticket'),
  222. 'ROLE_AGENT_DELETE_TICKET' => $translator->trans('Can delete ticket'),
  223. 'ROLE_AGENT_RESTORE_TICKET' => $translator->trans('Can restore trashed ticket'),
  224. 'ROLE_AGENT_ASSIGN_TICKET' => $translator->trans('Can assign ticket'),
  225. 'ROLE_AGENT_ASSIGN_TICKET_GROUP' => $translator->trans('Can assign ticket group'),
  226. 'ROLE_AGENT_UPDATE_TICKET_STATUS' => $translator->trans('Can update ticket status'),
  227. 'ROLE_AGENT_UPDATE_TICKET_PRIORITY' => $translator->trans('Can update ticket priority'),
  228. 'ROLE_AGENT_UPDATE_TICKET_TYPE' => $translator->trans('Can update ticket type'),
  229. 'ROLE_AGENT_ADD_NOTE' => $translator->trans('Can add internal notes to ticket'),
  230. 'ROLE_AGENT_EDIT_THREAD_NOTE' => $translator->trans('Can edit thread/notes'),
  231. 'ROLE_AGENT_MANAGE_LOCK_AND_UNLOCK_THREAD' => $translator->trans('Can lock/unlock thread'),
  232. 'ROLE_AGENT_ADD_COLLABORATOR_TO_TICKET' => $translator->trans('Can add collaborator to ticket'),
  233. 'ROLE_AGENT_DELETE_COLLABORATOR_FROM_TICKET' => $translator->trans('Can delete collaborator from ticket'),
  234. 'ROLE_AGENT_DELETE_THREAD_NOTE' => $translator->trans('Can delete thread/notes'),
  235. 'ROLE_AGENT_APPLY_WORKFLOW' => $translator->trans('Can apply prepared response on ticket'),
  236. 'ROLE_AGENT_ADD_TAG' => $translator->trans('Can add ticket tags'),
  237. 'ROLE_AGENT_DELETE_TAG' => $translator->trans('Can delete ticket tags')
  238. ],
  239. 'advanced' => [
  240. 'ROLE_AGENT_MANAGE_EMAIL_TEMPLATE' => $translator->trans('Can manage email templates'),
  241. 'ROLE_AGENT_MANAGE_GROUP' => $translator->trans('Can manage groups'),
  242. 'ROLE_AGENT_MANAGE_SUB_GROUP' => $translator->trans('Can manage Sub-Groups/ Teams'),
  243. 'ROLE_AGENT_MANAGE_AGENT' => $translator->trans('Can manage agents'),
  244. 'ROLE_AGENT_MANAGE_AGENT_PRIVILEGE' => $translator->trans('Can manage agent privileges'),
  245. 'ROLE_AGENT_MANAGE_TICKET_TYPE' => $translator->trans('Can manage ticket types'),
  246. 'ROLE_AGENT_MANAGE_CUSTOMER' => $translator->trans('Can manage customers'),
  247. 'ROLE_AGENT_MANAGE_WORKFLOW_MANUAL' => $translator->trans('Can manage Prepared Responses'),
  248. 'ROLE_AGENT_MANAGE_WORKFLOW_AUTOMATIC' => $translator->trans('Can manage Automatic workflow'),
  249. 'ROLE_AGENT_MANAGE_TAG' => $translator->trans('Can manage tags'),
  250. 'ROLE_AGENT_MANAGE_KNOWLEDGEBASE' => $translator->trans('Can manage knowledgebase'),
  251. 'ROLE_AGENT_MANAGE_AGENT_ACTIVITY' => $translator->trans("Can manage agent activity"),
  252. 'ROLE_AGENT_MANAGE_MARKETING_ANNOUNCEMENT' => $translator->trans("Can manage marketing announcement"),
  253. ]
  254. ];
  255. }
  256. public function generateCsrfToken($intention)
  257. {
  258. $csrf = $this->container->get('security.csrf.token_manager');
  259. return $csrf->getToken($intention)->getValue();
  260. }
  261. /**
  262. * This function will create content text from recived text, which we can use in meta content and as well in searching save like elastic
  263. * @param string $text String text
  264. * @param no. $lenght max return lenght string (which will convert to array)
  265. * @param boolean $returnArray what return type required
  266. * @return string/ array comma seperated/ []
  267. */
  268. public function createConentToKeywords($text, $lenght = 255, $returnArray = false)
  269. {
  270. //to remove all tags from text, if any tags are in encoded form
  271. $newText = preg_replace('/[\s]+/', ' ', str_replace($this->avoidArray, ' ', strtolower(strip_tags(html_entity_decode(strip_tags($text))))));
  272. if($lenght)
  273. $newText = substr($newText, 0, $lenght);
  274. return ($returnArray ? explode(' ', $newText) : str_replace(' ', ',', $newText));
  275. }
  276. public function requestHeadersSent()
  277. {
  278. return headers_sent() ? true : false;
  279. }
  280. /**
  281. * get current prefixes of member panel and knowledgebase
  282. */
  283. public function getCurrentWebsitePrefixes()
  284. {
  285. $filePath = $this->container->get('kernel')->getProjectDir() . '/config/packages/uvdesk.yaml';
  286. // get file content and index
  287. $file = file($filePath);
  288. foreach ($file as $index => $content) {
  289. if (false !== strpos($content, 'uvdesk_site_path.member_prefix')) {
  290. list($member_panel_line, $member_panel_text) = array($index, $content);
  291. }
  292. if (false !== strpos($content, 'uvdesk_site_path.knowledgebase_customer_prefix')) {
  293. list($customer_panel_line, $customer_panel_text) = array($index, $content);
  294. }
  295. }
  296. $memberPrefix = substr($member_panel_text, strpos($member_panel_text, 'uvdesk_site_path.member_prefix') + strlen('uvdesk_site_path.member_prefix: '));
  297. $knowledgebasePrefix = substr($customer_panel_text, strpos($customer_panel_text, 'uvdesk_site_path.knowledgebase_customer_prefix') + strlen('uvdesk_site_path.knowledgebase_customer_prefix: '));
  298. return [
  299. 'memberPrefix' => trim(preg_replace('/\s\s+/', ' ', $memberPrefix)),
  300. 'knowledgebasePrefix' => trim(preg_replace('/\s\s+/', ' ', $knowledgebasePrefix)),
  301. ];
  302. }
  303. /**
  304. * update your website prefixes
  305. */
  306. public function updateWebsitePrefixes($member_panel_prefix, $knowledgebase_prefix)
  307. {
  308. $filePath = $this->container->get('kernel')->getProjectDir() . '/config/packages/uvdesk.yaml';
  309. $website_prefixes = [
  310. 'member_prefix' => $member_panel_prefix,
  311. 'customer_prefix' => $knowledgebase_prefix,
  312. ];
  313. // get file content and index
  314. $file = file($filePath);
  315. foreach ($file as $index => $content) {
  316. if (false !== strpos($content, 'uvdesk_site_path.member_prefix')) {
  317. list($member_panel_line, $member_panel_text) = array($index, $content);
  318. }
  319. if (false !== strpos($content, 'uvdesk_site_path.knowledgebase_customer_prefix')) {
  320. list($customer_panel_line, $customer_panel_text) = array($index, $content);
  321. }
  322. }
  323. // save updated data in a variable ($updatedFileContent)
  324. $updatedFileContent = $file;
  325. // get old member-prefix
  326. $oldMemberPrefix = substr($member_panel_text, strpos($member_panel_text, 'uvdesk_site_path.member_prefix') + strlen('uvdesk_site_path.member_prefix: '));
  327. $oldMemberPrefix = preg_replace('/([\r\n\t])/','', $oldMemberPrefix);
  328. $updatedPrefixForMember = (null !== $member_panel_line) ? substr($member_panel_text, 0, strpos($member_panel_text, 'uvdesk_site_path.member_prefix') + strlen('uvdesk_site_path.member_prefix: ')) . $website_prefixes['member_prefix'] . PHP_EOL: '';
  329. $updatedPrefixForCustomer = (null !== $customer_panel_line) ? substr($customer_panel_text, 0, strpos($customer_panel_text, 'uvdesk_site_path.knowledgebase_customer_prefix') + strlen('uvdesk_site_path.knowledgebase_customer_prefix: ')) . $website_prefixes['customer_prefix'] . PHP_EOL : '';
  330. $updatedFileContent[$member_panel_line] = $updatedPrefixForMember;
  331. $updatedFileContent[$customer_panel_line] = $updatedPrefixForCustomer;
  332. // flush updated content in file
  333. file_put_contents($filePath, $updatedFileContent);
  334. $router = $this->container->get('router');
  335. $knowledgebaseURL = $router->generate('helpdesk_knowledgebase');
  336. $memberLoginURL = $router->generate('helpdesk_member_handle_login');
  337. $memberLoginURL = str_replace($oldMemberPrefix, $website_prefixes['member_prefix'], $memberLoginURL);
  338. return $collectionURL = [
  339. 'memberLogin' => $memberLoginURL,
  340. 'knowledgebase' => $knowledgebaseURL,
  341. ];
  342. }
  343. public static function getTimeFormats()
  344. {
  345. return array(
  346. 'm-d-y G:i' => 'm-d-y G:i (01-15-1991 13:00)',
  347. 'm-d-y h:ia' => 'm-d-y h:ia (01-15-1991 01:00pm)',
  348. 'd-m-y G:i' => 'd-m-y G:i (15-01-1991 13:00)',
  349. 'd-m-y h:ia' => 'd-m-y h:ia (15-01-1991 01:00pm)',
  350. 'd-m G:i' => 'd-m G:i (15-01 13:00)',
  351. 'd-m h:ia' => 'd-m h:ia (15-01 01:00pm)',
  352. 'd-M G:i' => 'd-M G:i (15-Jan 13:00)',
  353. 'd-M h:ia' => 'd-M h:ia (15-Jan 01:00pm)',
  354. 'D-m G:i' => 'D-m G:i (Mon-01 13:00)',
  355. 'D-m h:ia' => 'D-m h:ia (Mon-01 01:00pm)',
  356. 'Y-m-d H:i:sa' => 'Y-m-d H:i:s (1991-01-15 01:00:30pm)',
  357. );
  358. }
  359. public function generateCompleteLocalResourcePathUri($resource)
  360. {
  361. $resourceUriComponent = parse_url($resource);
  362. if (!empty($resourceUriComponent['scheme'])) {
  363. return $resource;
  364. }
  365. if (empty($this->completeLocalResourcePathUri)) {
  366. $router = $this->container->get('router');
  367. $scheme = $router->getContext()->getScheme();
  368. $siteurl = $this->container->getParameter('uvdesk.site_url');
  369. $baseurl = "$scheme://$siteurl";
  370. $urlComponents = parse_url($baseurl);
  371. $completeLocalResourcePathUri = "{$urlComponents['scheme']}://{$urlComponents['host']}";
  372. if (!empty($urlComponents['path'])) {
  373. $completeLocalResourcePathUri .= $urlComponents['path'];
  374. }
  375. if (substr($completeLocalResourcePathUri, -1) == '/') {
  376. $completeLocalResourcePathUri = substr($completeLocalResourcePathUri, 0, -1);
  377. }
  378. $this->completeLocalResourcePathUri = $completeLocalResourcePathUri;
  379. }
  380. if ($resource[0] != '/') {
  381. $resource = "/$resource";
  382. }
  383. return $this->completeLocalResourcePathUri . $resource;
  384. }
  385. public function getAvailableUserAccessScopes($user, $userInstance)
  386. {
  387. $supportRole = $userInstance->getSupportRole();
  388. $isAdminAccessGranted = in_array($supportRole->getId(), [1, 2]) ? true : false;
  389. $availableSupportPrivileges = $this->getSupportPrivelegesResources();
  390. $resolvedAvailableSupportPrivileges = [];
  391. foreach ($availableSupportPrivileges as $index => $collection) {
  392. foreach ($collection as $privilegeId => $privilegeDescription) {
  393. $resolvedAvailableSupportPrivileges[] = $privilegeId;
  394. }
  395. }
  396. if (false == $isAdminAccessGranted) {
  397. $assignedUserSupportPrivileges = $this->userService->getAssignedUserSupportPrivilegeDetails($user, $userInstance);
  398. $resolvedAssignedUserSupportPrivileges = [];
  399. foreach ($assignedUserSupportPrivileges as $assignedSupportPrivilege) {
  400. foreach ($assignedSupportPrivilege['privileges'] as $privilegeId) {
  401. $resolvedAssignedUserSupportPrivileges[] = $privilegeId;
  402. }
  403. }
  404. return array_map(function ($supportPrivilege) {
  405. return strtolower(str_replace('ROLE_AGENT_', '', $supportPrivilege));
  406. }, $resolvedAssignedUserSupportPrivileges);
  407. }
  408. return array_map(function ($supportPrivilege) {
  409. return strtolower(str_replace('ROLE_AGENT_', '', $supportPrivilege));
  410. }, $resolvedAvailableSupportPrivileges);
  411. }
  412. }